Valid Sudoku

Published by

on

Problem

https://leetcode.com/problems/valid-sudoku

Solution

// 1. row 순회해서 valid 한지 확인
// 2. col 순회해서 valid 한지 확인
// 3. n 번째 grid 의 첫번째 좌표 = (3 * (n%3), 3 * (n/3)) 기준으로 순회해서 valid 한지 확인
class Solution {
    public boolean isValidSudoku(char[][] board) {
        if (!isValidRow(board)) {
            System.out.println("Invalid Row!");
            return false;
        }

        if (!isValidCol(board)) {
            System.out.println("Invalid Col!");
            return false;
        }

        if (!isValidGrid(board)) {
            System.out.println("Invalid Grid!");
            return false;
        }

        return true;
    }

    private boolean isValidRow(char[][] board) {
        Set<Character> visited;
        for (int i=0;i<9;i++) {
            visited = new HashSet<>();
            for (int j=0;j<9;j++) {
                char c = board[i][j];
                if (c == '.') {
                    continue;
                }
                // System.out.println("(" + i + ", " + j +"):" + c);
                if (visited.contains(c)){
                    return false;
                }
                visited.add(c);
            }
        }
        return true;
    }

    private boolean isValidCol(char[][] board) {
        Set<Character> visited;
        for (int i=0;i<9;i++) {
            visited = new HashSet<>();
            for (int j=0;j<9;j++) {
                char c = board[j][i];
                if (c == '.') {
                    continue;
                }
                if (visited.contains(c)){
                    return false;
                }
                visited.add(c);
            }
        }
        return true;
    }

    private boolean isValidGrid(char[][] board) {
        Set<Character> visited;
        for (int n=0;n<9;n++) {
            visited = new HashSet<>();
            int x = 3 * (n % 3);
            int y = 3 * (n / 3);

            // System.out.println("["+n+"] - x: " + x +", y : " + y);
            for (int i=x;i<x+3;i++) {
                for (int j=y;j<y+3;j++) {
                    // System.out.print("("+i+","+j+"): ");
                    char c = board[i][j];
                    // System.out.println(c);
                    if (c == '.') {
                        continue;
                    }
                    if (visited.contains(c)){
                        return false;
                    }
                    visited.add(c);
                }
            }
        }
        return true;
    }
}
  • Row 와 Col과 달리 Grid에 대한 로직을 구하는것 이 포인트.
    • 방법 #1. 각 Grid 의 시작점(왼쪽 상단) 을 구한다
      • 이 때, 숫자를 다 나열해보고 규칙을 찾는것이 좋다!
        • n = 0 1 2 3 4 5 6 7 8
          x = 0 3 6 0 3 6 0 3 6
          y = 0 0 0 3 3 3 6 6 6
          => x = 3 * (n % 3),
            y = 3 * (n / 3)
    • 방법 #2. 각 Grid 의 번호를 구한다
      • 행/열의 숫자를 적어보고 규칙을 찾는다!
        • n = (x / 3) * 3 + (y / 3)

Leave a comment