您的位置:首页 > 其它

Leetcode - Valid Sudoku

2016-04-10 15:13 316 查看

Question

Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.

The Sudoku board could be partially filled, where empty cells are filled with the character ‘.’.



简述一下检查的规则:

1. 每一行中数字1~9只能出现一次;

2. 每一列中数字1~9只能出现一次;

3. 9个子格子中数字1~9只能出现一次;

Note

A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.

Java Code

public boolean isValidSudoku(char[][] board) {
//检查所有行
for(int i = 0; i < 9; ++i) {
if(check(board[i]))
return false;
}

char[] temp = new char[9];//存放当前需要检查的字符

//检查所有列
for(int i = 0; i < 9; ++i) {
for(int j = 0; j < 9; ++j)
temp[j] = board[j][i];

if(check(temp))
return false;
}

//检查所有sub-boxes
for(int xStep = 0; xStep < 9; xStep += 3) {
for(int yStep = 0; yStep < 9; yStep += 3) {
for(int i = 0; i < 3; ++i)
for(int j = 0; j < 3; ++j)
temp[j + 3*i] = board[i + xStep][j + yStep];

if(check(temp))
return false;
}
}

//检查都通过,则是有效的数独
return true;
}

//检查当前区域是否有重复数字,有重复则返回true
//版本一:直接两两字符之间比较
public boolean check(char[] str) {
int j;
char c;
for(int i=0; i<str.length - 1; ++i) {
c = str[i];
if(c == '.')
continue;

for(j = i + 1;j<str.length;++j){
if(c == str[j])
return true;
}
}
return false;
}

//版本二: 使用HashSet
public boolean check(char[] str, boolean b) {
HashSet<String> hs = new HashSet<>();
for(int i = 0; i < 9; ++i) {
if (str[i] == '.')
continue;

if(!hs.add(str[i]+""))
return true;
}
return false;
}


说明

本题没有太多的技巧性可言,主要是取出9个子格子的过程要注意二维数组的索引变化规律,另外检查temp字符数组是否有重复字符的方式有多种,由于temp数组只有9个元素,所以这里直接比较比用Set处理更加高效
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode Sudoku character