您的位置:首页 > 其它

leetcode做题总结,题目Valid Sudoku 2012/03/03

2014-11-29 09:48 351 查看
数独游戏,横,竖,方框的9个数都不能相同,我的方法是用boolean数组即可。

public class Solution {
public boolean isValidSudoku(char[][] board) {
boolean[] b=new boolean[9];
for(int i=0;i<9;i++){
for(int j=0;j<9;j++){
if(board[i][j]=='.')
continue;
if(b[Integer.parseInt(board[i][j]+"")-1]==false)
b[Integer.parseInt(board[i][j]+"")-1]=true;
else
return false;
}
b=new boolean[9];
}
for(int i=0;i<9;i++){
for(int j=0;j<9;j++){
if(board[j][i]=='.')
continue;
if(b[Integer.parseInt(board[j][i]+"")-1]==false)
b[Integer.parseInt(board[j][i]+"")-1]=true;
else
return false;
}
b=new boolean[9];
}
for(int x=0;x<7;x+=3){
for(int y=0;y<7;y+=3){
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
if(board[x+i][y+j]=='.')
continue;
if(b[Integer.parseInt(board[x+i][y+j]+"")-1]==false)
b[Integer.parseInt(board[x+i][y+j]+"")-1]=true;
else
return false;
}
}
b=new boolean[9];
}
}
return true;

}
}


Update 2015/09/30:

public class Solution {
public boolean isValidSudoku(char[][] board) {
if (board.length !=9 || board[0].length !=9) {
return false;
}
for (int i = 0; i < 9; i++){
boolean[] check = new boolean[9];
for (int j = 0; j < 9; j++){
if (board[i][j] == '.')
continue;
if (check[(int)(board[i][j] - '1')]){
return false;
}
check[(int)(board[i][j]-'1')] = true;
}
}
for (int j = 0; j < 9; j++){
boolean[] check = new boolean[9];
for (int i = 0; i < 9; i++){
if (board[i][j] == '.')
continue;
if (check[(int)(board[i][j]- '1')]){
return false;
}
check[(int)(board[i][j]-'1')] = true;
}
}

for (int i = 0; i < 9; i=i+3){

for (int j = 0; j < 9; j=j+3){
boolean[] check = new boolean[9];
for (int k = i; k < i+3;k++){
for (int r = j; r < j+3;r++){
if (board[k][r] == '.')
continue;
if (check[(int)(board[k][r]-'1')]){
return false;
}
check[(int)(board[k][r]-'1')] = true;
}
}
}
}
return true;

}
}


update 2015/10/09: 主要是改变了第三个方格检查,这样就可以使用三个数组一次性扫过检查

public class Solution {
public boolean isValidSudoku(char[][] board) {
if (board.length !=9 || board[0].length !=9) {
return false;
}
for (int i = 0; i < 9; i++){
boolean[] check = new boolean[9];
for (int j = 0; j < 9; j++){
if (board[i][j] == '.')
continue;
if (check[(int)(board[i][j] - '1')]){
return false;
}
check[(int)(board[i][j]-'1')] = true;
}
}
for (int j = 0; j < 9; j++){
boolean[] check = new boolean[9];
for (int i = 0; i < 9; i++){
if (board[i][j] == '.')
continue;
if (check[(int)(board[i][j]- '1')]){
return false;
}
check[(int)(board[i][j]-'1')] = true;
}
}
for (int i = 0; i < 9; i++){
boolean[] check = new boolean[9];
for (int j = 0; j < 9; j++){
if (board[3 * (i / 3) + (j / 3)][3 * (i % 3) + (j % 3)] == '.')
continue;
if (check[board[3 * (i / 3) + (j / 3)][3 * (i % 3) + (j % 3)] - '1'])
return false;
check[board[3 * (i / 3) + (j / 3)][3 * (i % 3) + (j % 3)] - '1'] = true;
}
}
return true;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: