Java 5 ms solution - concise with explanation


  • 1
    R
       public boolean isValidSudoku(char[][] board) {
        if(board == null || board.length != 9 || board[0].length != 9)
            return false;
            
        // row map - to map each row from 0 to 9 with digits from 0 - 9 using boolean(i.e for each row) -->[rownum][digit]
    	boolean row[][] = new boolean[9][9];
    	// col map - similar as above
    	boolean col[][] = new boolean[9][9];
    	// box map - numbered from 00, 01, 02, 10, 11, 12, 20, 21, 22. Each box with boolean values  0-9 for mapping digits 
    	boolean box[][][] = new boolean[3][3][9];
    	for (int r = 0; r < board.length; r++) {
    		for (int c = 0; c < board[0].length; c++) {
    			char ch = board[r][c];
    			if (ch == '.')
    				continue;
    			else if (ch >= '1' && ch <= '9') {
    				int num = ch - '0' - 1; // -1 beacuse row, col and box maps indices are 0 based
    
    				if (row[r][num])
    					return false;
    				row[r][num] = true;
    				if (col[c][num])
    					return false;
    				col[c][num] = true;
    				if (box[r / 3][c / 3][num])
    					return false;
    				box[r / 3][c / 3][num] = true;
    			} else
    				return false;
    		}
    	}
    	return true;
    }

Log in to reply
 

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