Thinking process

follow the rules of sudoku

  • check the row
  • check the column
  • check the sub-box

How to iterate over the matrix one time?

https://discuss.leetcode.com/topic/9748/shared-my-concise-java-code

public class Solution {
    public boolean isValidSudoku(char[][] board) {
        for (int i = 0; i < 9; ++i) {
            HashSet<Character> rowSet = new HashSet<>();
            HashSet<Character> colSet = new HashSet<>();
            HashSet<Character> subBoxSet = new HashSet<>();

            for (int j = 0; j < 9; ++j) {
                if (board[i][j] != '.' && !rowSet.add(board[i][j])) {
                    return false;
                }

                if (board[j][i] != '.' && !colSet.add(board[j][i])) {
                    return false;
                }

                int rowBase = 3 * (i / 3);
                int colBase = 3 * (i % 3);
                if (board[rowBase + j / 3][colBase + j % 3] != '.' && !subBoxSet.add(board[rowBase + j / 3][colBase + j % 3])) {
                    return false;
                }


            }
        }

        return true;
    }
}

results matching ""

    No results matching ""