【LeetCode】036.Valid Sudoku

来源:互联网 发布:淘宝访客下降怎么解决 编辑:程序博客网 时间:2024/05/22 12:39

题目:

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.

解答:

既然不要求必须可解,那么只要判断不重复即可,即每行、没列、每个九宫格里都不重复。使用HashMap进行重复判断。

有点难度的地方在于,第i个九宫格里第j个格子的表示方法,行为:i/3*3+j/3,列为:i%3*3+j%3;


代码:

public class Solution {    public boolean isValidSudoku(char[][] board) {for(int i=0;i<9;i++){HashMap<Character,Integer> row = new HashMap<Character,Integer>();HashMap<Character,Integer> column = new HashMap<Character,Integer>();HashMap<Character,Integer> block = new HashMap<Character,Integer>();for(int j=0;j<9;j++){if(board[i][j] != '.'){if(row.containsKey(board[i][j]))return false;elserow.put(board[i][j], 1);}if(board[j][i] != '.'){if(column.containsKey(board[j][i]))return false;elsecolumn.put(board[j][i], 1);}if(board[i/3*3+j/3][i%3*3+j%3] != '.'){if(block.containsKey(board[i/3*3+j/3][i%3*3+j%3]))return false;elseblock.put(board[i/3*3+j/3][i%3*3+j%3], 1);}}}return true;}}





0 0
原创粉丝点击