Wednesday, December 2, 2015

[leetcode]Valid Sudoku

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
public class Solution {
    public boolean isValidSudoku(char[][] board) {
        if (board == null || board.length != 9 || board[0].length != 9) return false;
        boolean lookup[];
        boolean lookCol[];
        for (int i = 0; i < 9; i++){
         lookup = new boolean[9];
         lookCol = new boolean[9];
         for (int j = 0; j < 9; j++){
          if (board[i][j] != '.'){
           int index = board[i][j] - '0'-1;
           if (lookup[index]) return false;
           lookup[index] = true;
          }
          if (board[j][i] != '.'){
           int index2 = board[j][i] -'0'-1;
           if (lookCol[index2]) return false;
           lookCol[index2] = true;
          }
         }
        }
        
        for (int i = 0; i < 9; i+=3){
         for (int j = 0; j < 9; j+=3){
          lookup = new boolean[9];
          lookCol = new boolean[9];
          for (int k = i; k < i+3; k++){
           for (int q = j; q < j+3; q++){
            if (board[k][q] != '.'){
             int index = board[k][q] - '0'-1;
             if (lookup[index]) return false;
             lookup[index] = true;
            }
            if (board[q][k] != '.'){
             int index2 = board[q][k] -'0'-1;
             if (lookCol[index2]) return false;
             lookCol[index2] = true;
            }
           }
          }
         }
        }       
        return true; 
    }
}

No comments:

Post a Comment