Using boolean array instead of HashMap Java simple solution


  • 0
    L

    Your runtime beats 86.28% of java submissions.
    501 / 501 test cases passed.
    Status: Accepted
    Runtime: 29 ms

    public class ValidSudoku {
        private static final char EMPTY ='.';
    
        public boolean isValidSudoku(char[][] board) {
            boolean[][] rows, cols, subBoxs;
            rows = new boolean[9][10]; //1 based index.
            cols = new boolean[9][10];
            subBoxs = new boolean[9][10];
    
            char ch;
            int num, boxId;
            for (int i = 0; i < 9; i++) {
                for (int j = 0; j < 9; j++) {
                    ch = board[i][j];
                    if (ch == EMPTY)
                        continue;
                    num = ch - '0';
                    boxId = (i / 3) * 3 + j / 3;
                    //System.out.printf("boxId=%d, board[%d,%d]=%d%n", boxId, i, j, num);
    
                    if (rows[i][num]) return false;
                    if (cols[j][num]) return false;
                    if (subBoxs[boxId][num]) return false;
                    rows[i][num] = true;
                    cols[j][num] = true;
                    subBoxs[boxId][num] = true;
                }
            }
    
            return true;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.