Valid Sudoku

题目
Determine if a Sudoku is valid.

答案

class Solution {
    int[][] dx = {{1, 0, 0}, {1, 0, 0}, {1, 0, 1}, {1, 0, 0}, {1, 0, 0}, {1, 0, 1}, {1, 0, 0}, {1, 0, 0}};
    int[][] dy = {{0, 1, 1}, {0, 1, 1}, {0, 1, 0}, {0, 1, -1}, {0, 1, -1}, {0, 1, 0}, {0, 1, 1}, {0, 1, 1}};

    // make sure no duplicate in same row, same column, and same sub board
    public boolean isValidSudoku(char[][] board) {

        for(int i = 0; i < board[0].length; i++) {
            if(!isValid(board, 0, i, 0)) return false;
        }

        for(int i = 0; i < board.length; i++) {
            if(!isValid(board, i, 0, 1)) return false;
        }

        for(int i = 0; i < board.length; i = i + 3) {
            for(int j = 0; j < board[0].length; j = j + 3) {
                if(!isValid(board, i, j, 2)) return false;
            }
        }
        return true;
    }
    private boolean isValid(char[][] board, int row, int col, int dir) {
        Set set = new HashSet<>();
        set.add(board[row][col]);
        int newRow = row, newCol = col;
        for(int i = 0; i < 8; i++) {
            newRow = newRow + dx[i][dir];
            newCol = newCol + dy[i][dir];
            if(board[newRow][newCol] == '.') continue;
            if(!set.add(board[newRow][newCol])) return false;
        }
        return true;
    }
}

你可能感兴趣的:(Valid Sudoku)