389 判断数独是否合法

原题网址:http://www.lintcode.com/zh-cn/problem/valid-sudoku/#

请判定一个数独是否有效。

该数独可能只填充了部分数字,其中缺少的数字用 . 表示。

 注意事项

一个合法的数独(仅部分填充)并不一定是可解的。我们仅需使填充的空格有效即可。

样例

The following partially filed sudoku is valid.

 

 1 #include <iostream>
 2 #include <vector>
 3 #include <math.h>
 4 #include <string>
 5 #include <algorithm>
 6 using namespace std;
 7 
 8 
 9 class Solution {
10 public:
11 bool NotRepeat(vector<int> temp) //判断数组是否有重复元素;
12 {
13     for (int n=0;n<(int)temp.size();n++)
14     {
15         for (int m=n+1;m<(int)temp.size();m++)
16         {
17             if (temp[n]==temp[m])
18             {
19                 return false; 
20             }
21         }
22     }
23     return true;
24 }
25 
26 
27 bool isValidSudoku(vector<vector<char>> &board)
28 {
29     for (int i=0;i<9;i++)
30     {
31         //行;
32         vector<int> temprow;
33         for (int j=0;j<9;j++)
34         {
35             if (board[i][j]!='.')
36             {
37                 temprow.push_back(board[i][j]);
38             }
39         }
40         if (NotRepeat(temprow)==false)
41         {
42             return false;
43         }
44         //列;
45         vector<int> tempcol;
46         for (int j=0;j<9;j++)
47         {
48             if (board[j][i]!='.')
49             {
50                 tempcol.push_back(board[j][i]);
51             }
52         }
53         if (NotRepeat(tempcol)==false)
54         {
55             return false;
56         }
57     }
58 
59     //宫;
60     int row=0;
61     int col=0;
62     for (;row<9;row=row+3)
63     {
64         for (;col<9;col=col+3)
65         {
66             vector<int> gong;
67             for (int i=row;i<row+3;i++)
68             {
69                 for (int j=col;j<col+3;j++)
70                 {
71                     if (board[i][j]!='.')
72                     {
73                         gong.push_back(board[i][j]);
74                     }
75                 }
76             }
77             if (NotRepeat(gong)==false)
78             {
79                 return false;
80             }
81 
82         }
83     }
84 
85     return true;
86 }
87 };

参考:

https://www.cnblogs.com/Smallhui/p/5540835.html

https://blog.csdn.net/witnessai1/article/details/49205847

posted @ 2018-03-23 20:01  eeeeeeee鹅  阅读(416)  评论(0编辑  收藏  举报