[LeetCode][Java]Valid Sudoku

최지수·2021년 12월 19일
0

Algorithm

목록 보기
38/77
post-thumbnail

문제

Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:

Each row must contain the digits 1-9 without repetition.
Each column must contain the digits 1-9 without repetition.
Each of the nine 3 x 3 sub-boxes of the grid must contain the digits 1-9 without repetition.

Note:

  • A Sudoku board (partially filled) could be valid but is not necessarily solvable.
  • Only the filled cells need to be validated according to the mentioned rules.

접근

스도쿠 문제였어요. 3 x 3 단위로 블럭을 확인하고 각 행과 열이 1~9사이의 값 중 중복이 되지 않으면 되는 것이었고, 이에 대해 체크를 하면 되는 문제였어요.

근데 LeetCode 특성상 이런 문제는 항상 응용 문제가 나오던데....준비해야겠네요.

답안

class Solution {

    public boolean isValidSudoku(char[][] board) {
        // Block
        for(int y = 0; y < 9; y += 3){
            for(int x = 0; x < 9 ; x += 3){
                if(!isBlockValid(board, y, x))
                    return false;
            }
        }

        // Row
        for(int y = 0; y < 9; ++y){
            if(!isRowValid(board, y))
                return false;
        }

        // Col
        for(int x = 0; x < 9; ++x){
            if(!isColValid(board, x))
                return false;
        }

        return true;
    }

    private boolean isBlockValid(char[][] board, int row, int col){
        boolean[] check = new boolean[10];
        for(int y = row; y < row + 3; ++y){
            for(int x = col; x < col + 3; ++x){
                if('1' <= board[y][x] && board[y][x] <= '9'){
                    int value = Character.getNumericValue(board[y][x]);
                    if(check[value])
                        return false;
                    check[value] = true;
                }
            }
        }
        return true;
    }

    private boolean isRowValid(char[][] board, int row){
        boolean[] check = new boolean[10];
        for(int x = 0; x < 9; ++x){
            if('1' <= board[row][x] && board[row][x] <= '9'){
                int value = Character.getNumericValue(board[row][x]);
                if(check[value])
                    return false;
                check[value] = true;
            }
        }

        return true;
    }

    private boolean isColValid(char[][] board, int col){
        boolean[] check = new boolean[10];
        for(int y = 0; y < 9; ++y){
            if('1' <= board[y][col] && board[y][col] <= '9'){
                int value = Character.getNumericValue(board[y][col]);
                if(check[value])
                    return false;
                check[value] = true;
            }
        }

        return true;
    }
}
profile
#행복 #도전 #지속성

0개의 댓글