首页 > 代码库 > Leetcode-Valid Sudoku
Leetcode-Valid Sudoku
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.
Solution:
1 public class Solution { 2 public boolean isValidSudoku(char[][] board) { 3 int rowNum = board.length; 4 if (rowNum!=9) return false; 5 int colNum = board[0].length; 6 if (colNum!=9) return false; 7 8 for (int i=0;i<rowNum;i++) 9 if (!checkArea(board,i,0,1,9)) return false;10 11 for (int i=0;i<colNum;i++)12 if (!checkArea(board,0,i,9,1)) return false;13 14 int[] index = new int[]{0,3,6};15 for (int i=0;i<3;i++)16 for (int j=0;j<3;j++)17 if (!checkArea(board,index[i],index[j],3,3)) return false;18 19 return true;20 21 22 }23 24 public boolean checkArea(char[][] board, int x, int y, int rowNum, int colNum){25 Set<Integer> set = new HashSet<Integer>();26 for (int i=0;i<rowNum;i++)27 for (int j=0;j<colNum;j++)28 if (board[x+i][y+j]!=‘.‘){29 int val = board[x+i][y+j]-‘0‘;30 if (val<0 || val>9) return false;31 if (set.contains(val))32 return false;33 else set.add(val);34 }35 36 return true;37 38 }39 40 }
Leetcode-Valid Sudoku
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。