码迷,mamicode.com
首页 > 其他好文 > 详细

Valid Sudoku

时间:2016-07-13 13:58:46      阅读:99      评论:0      收藏:0      [点我收藏+]

标签:

Determine whether a Sudoku is valid.

The Sudoku board could be partially filled, where empty cells are filled with the character ..

 Notice

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

Example

The following partially filed sudoku is valid.

技术分享

分析:

我们得检查行,列,和小的正方形。小的正方形检查起来比较麻烦。

 1 class Solution {
 2     /**
 3       * @param board: the board
 4         @return: wether the Sudoku is valid
 5       */
 6     public boolean isValidSudoku(char[][] board) {
 7         boolean[] visited = new boolean[9];
 8         
 9         // row
10         for(int i = 0; i < 9; i++){
11             Arrays.fill(visited, false);
12             for(int j = 0; j < 9; j++){
13                 if(!process(visited, board[i][j]))
14                     return false;
15             }
16         }
17         
18         //col
19         for(int i = 0; i < 9; i++){
20             Arrays.fill(visited, false);
21             for(int j = 0; j < 9; j++){
22                 if(!process(visited, board[j][i]))
23                     return false;
24             }
25         }
26         
27         // sub matrix
28         for(int i = 0; i < 9; i += 3){
29             for(int j = 0; j < 9; j += 3){
30                 Arrays.fill(visited, false);
31                 for(int k = 0; k < 9; k++){
32                     if(!process(visited, board[i + k / 3][ j + k % 3]))
33                     return false;                   
34                 }
35             }
36         }
37         return true;
38     }
39     
40     private boolean process(boolean[] visited, char digit){
41         if(digit == .){
42             return true;
43         }
44         
45         int num = digit - 0;
46         if ( num < 1 || num > 9 || visited[num-1]){
47             return false;
48         }
49         
50         visited[num - 1] = true;
51         return true;
52     }
53 };

 

 

Valid Sudoku

标签:

原文地址:http://www.cnblogs.com/beiyeqingteng/p/5666426.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!