解法都在代码里,不懂就留言或者私信,比第一题稍微难点
java">class Solution {public static boolean isValidSudoku(char[][] board) {/**rowExists[i][j]代表第i行是否存在数据j+1*/boolean[][] rowExists = new boolean[9][9];/**rowExists[i][j]代表第i列是否存在数据j+1*/boolean[][] colExists = new boolean[9][9];/**rowExists[i][j]代表第i个格子是否存在数据j+1*/boolean[][] bucketExists = new boolean[9][9];for(int i = 0; i < board.length; i++) {for(int j = 0; j < board[i].length; j++) {if(board[i][j] == '.') {continue;}/**如果这个行已经存在这个数字了,返回false*/if(rowExists[i][board[i][j] - '1']) {return false;}/**如果原来没有,现在这个数就是,有了记录一下*/rowExists[i][board[i][j]-'1'] = true;/**如果这个列已经存在这个数字了,返回false*/if(colExists[j][board[i][j]-'1']) {return false;}/**如果原来没有,现在这个数就是,有了记录一下*/colExists[j][board[i][j]-'1'] = true;/**计算当前应该在哪个桶,这里注意bucketnum的计算*/int bucketNum = j / 3 + (i / 3)*3;if(bucketExists[bucketNum][board[i][j]-'1']) {return false;}bucketExists[bucketNum][board[i][j]-'1'] = true;}}return true;}
}
运行结果