标签:
题目:
判断数独是否合法
class Solution { /** * @param board: the board @return: wether the Sudoku is valid */ public boolean isValidSudoku(char[][] board) { boolean[] visited = new boolean[9]; //row for(int i=0;i<9;i++){ Arrays.fill(visited,false); //填充visited数组中的每个元素都是false for(int j=0;j<9;j++){ if(!process(visited,board[i][j])) return false; } } //col for(int i=0;i<9;i++){ Arrays.fill(visited,false); for(int j=0;j<9;j++) if(!process(visited,board[j][i])) return false; } //sub matrix for(int i=0;i<9;i+=3) for(int j=0;j<9;j+=3){ Arrays.fill(visited,false); for(int k = 0;k<9;k++) if(!process(visited,board[i+ k/3][j + k%3])) return false; } return true; } private boolean process(boolean[] visited,char dight){ if(dight==‘.‘) return true; int num = dight - ‘0‘; if(num<1 || num>9 || visited[num-1]) return false; visited[num-1] = true; return true; } };
总耗时: 822 ms
Python程序:
class Solution: # @param board, a 9x9 2D array # @return a boolean def isValidSudoku(self, board): # sub matrix for i in range(0,9,3): for j in range(0,9,3): visited = [False]*9 for k in range(3): m = i + k n = j + k if(self.process(visited,board[m][n])==False): return False # row for i in range(9): visited = [False]*9 for j in range(9): if(self.process(visited,board[i][j])==False): return False # col for j in range(9): visited = [False]*9 for i in range(9): if(self.process(visited,board[i][j])==False): return False return True def process(self,visited,digit): if digit==‘.‘: return True num = int(digit) if(num<1 or num>9 or visited[num-1]==True): return False visited[num-1] = True return True
总耗时: 148 ms
在判断3*3矩阵时候,根据我的这样方法很简单的哦
还有就是直判断行和列是否满足条件也能AC
所以我把判断小矩阵是否1-9组成放在了最上面
lintcode 容易题:Valid Sudoku 判断数独是否合法
标签:
原文地址:http://www.cnblogs.com/theskulls/p/4869025.html