LeetCode题解:Valid Sudoku

来源:互联网 发布:jquery 转js 编辑:程序博客网 时间:2024/05/21 18:19

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.

题意:判断数独是否有效(不是是否可解/解的答案),只要行/列没有重复数字就是有效

解决思路:利用HashSet,先判断行列是否有效,把九宫格划分为9个小格子,再判断小格子是否有效

代码:

public class Solution {    public boolean isValidSudoku(char[][] board) {        for(int i = 0; i < 9; i++){            if(!isPartiallyValid(board, i, 0, i, 8)){                return false;            }            if(!isPartiallyValid(board, 0, i, 8, i)){                return false;            }        }        for(int i = 0; i < 3; i++){            for(int j = 0; j < 3; j++){                if(!isPartiallyValid(board, i * 3, 3 * j, i * 3 + 2, 3 * j + 2)){                    return false;                }            }        }        return true;    }    private boolean isPartiallyValid(char[][] board, int startX, int startY, int endX, int endY){        Set set = new HashSet();        for(int i = startX; i <= endX;i++){            for(int j = startY; j <= endY; j++){                if(board[i][j] != '.'){                    if(!set.add(board[i][j])){                        return false;                    }                }            }        }        return true;    }}
0 0
原创粉丝点击