您的位置:首页 > 产品设计 > UI/UE

LeetCode 36 Valid Sudoku My Submissions Question

2016-03-28 16:18 615 查看
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
'.'
.



A partially filled sudoku which is valid.

Note:

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

题意:要求判断数独当前所填的数字是否有效,无需判断当前这个数独是否有解。

逻辑:1.每个九宫格square里面的数字不得重复。

2.每一行数字不得重复。

3.每一列数字不得重复。

以上3个条件,需要同时满足,否则数独无效。注意每个square和行列的对应关系。

代码实现如下:

public boolean isValidSudoku(char[][] board) {
List<Set<Character>> square = new ArrayList<Set<Character>>();
List<Set<Character>> row = new ArrayList<Set<Character>>();
List<Set<Character>> column = new ArrayList<Set<Character>>();
for (int i = 0; i < 9; i++) {
square.add(new HashSet<Character>());
row.add(new HashSet<Character>());
column.add(new HashSet<Character>());
}
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (board[i][j] == '.') continue;
if (square.get(i / 3 * 3 + j / 3).contains(board[i][j]) || row.get(i).contains
(board[i][j])
|| column
.get(j).contains(board[i][j])) return false;
square.get(i / 3 * 3 + j / 3).add(board[i][j]);
row.get(i).add(board[i][j]);
column.get(j).add(board[i][j]);
}
}
return true;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: