Valid Sodoku Simple Java Solution


  • 0
    P

    Simple solutions beats 80% of Java submissions.

    class Solution {
        public boolean isValidSudoku(char[][] board) {
            boolean[] filledX = new boolean[9];
            boolean[] filledY = new boolean[9];
            int val = 0;
            for (int i = 0; i < 9; i++) {
                for (int j = 0; j < 9; j++) {
                    if (board[i][j] != '.') {
                        val = board[i][j] - '0' - 1;
                        if (filledX[val]) {
                            return false;
                        }
                        filledX[val] = true;
                    }
                    if (board[j][i] != '.') {
                        val = board[j][i] - '0' - 1;
                        if (filledY[val]) {
                            return false;
                        }
                        filledY[val] = true;
                    }
                }
                filledX = new boolean[9];
                filledY = new boolean[9];
            }
            
            for (int x = 0; x < 9; x += 3) {
                for (int y = 0; y < 9; y += 3) {
                    for (int i = 0; i < 3; i++) {
                        for (int j = 0; j < 3; j++) {
                            if (board[i+x][j+y] != '.') {
                                val = board[i+x][j+y] - '0' - 1;
                                if (filledX[val]) {
                                    return false;
                                }
                                filledX[val] = true;
                            }
                        }
                    }
                    filledX = new boolean[9];
                }
            }
            
            return true;
        }
    }
    

Log in to reply
 

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