LeetCode 1. 10 有效的数独
Posted 年轻人,戒骄戒躁
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 1. 10 有效的数独相关的知识,希望对你有一定的参考价值。
1 #include <iostream> 2 #include <time.h> 3 #include <stdio.h> 4 #include <set> 5 #include<vector> 6 #include<map> 7 using namespace std; 8 9 bool square_(int pad, int mag,vector<vector<char>>& board) { 10 map<char, int> m; 11 m.clear(); 12 int i, j; 13 bool ok=1; 14 for (i=pad; i < pad+3; ++i) { 15 for (j=mag; j < mag+3; ++j) 16 { 17 if (m[board[i][j]] == 0) { 18 if (board[i][j] != \'.\') 19 m[board[i][j]]++; 20 } 21 else { 22 // cout << "(" << i << " , " << j << ")" << board[i][j] << "方格重复!" << endl; 23 ok = 0; 24 return ok; 25 } 26 } 27 } 28 return ok; 29 } 30 bool isValidSudoku(vector<vector<char>>& board) { 31 bool ok=1;//默认成功 32 map<char, int> m; 33 //纵向*9 34 for (size_t i = 0; i < 9; ++i) { 35 m.clear(); 36 for (size_t j = 0; j < 9; ++j) { 37 if (m[board[j][i]] == 0){ 38 if(board[j][i]!=\'.\') 39 m[board[j][i]]++;} 40 else { 41 // cout <<"("<<j<<" , "<<i<<")"<< board[j][i] << "纵向重复!" << endl; 42 ok = 0; 43 return ok ; 44 } 45 } 46 } 47 //横向*9 48 for (size_t i = 0; i < 9; ++i) { 49 m.clear(); 50 for (size_t j = 0; j < 9; ++j) { 51 if (m[board[i][j]] == 0) { 52 if (board[i][j] != \'.\') 53 m[board[i][j]]++; 54 } 55 else { 56 // cout << "(" << i << " , " << j<< ")" << board[i][j] << "横向重复!" << endl; 57 ok = 0; 58 return ok; 59 } 60 } 61 } 62 //小方格*9 63 int i = 0; int j = 0; int pad=0; int mag = 0; 64 for (j = 0; j < 3; ++j) { 65 for (i = 0; i < 3; i++) 66 { 67 ok = square_(pad, mag, board); 68 if (ok == 0) 69 return ok; 70 pad += 3; 71 } 72 mag += 3; 73 pad = 0; 74 } 75 return ok; 76 } 77 78 int main() 79 { 80 vector<vector<char>> v1; 81 vector<char> v2; 82 int n; 83 char x; 84 printf("输入数独: \\n"); 85 //scanf("%d", &n); 86 for (size_t j = 0; j < 9; ++j) { 87 v2.clear(); 88 for (size_t i = 0; i < 9; ++i) 89 { 90 while (1) { 91 scanf("%c", &x); 92 if ((x >= \'1\' && x <= \'9\') || x == \'.\') 93 break; 94 } 95 v2.push_back(x); 96 } 97 v1.push_back(v2); 98 } 99 100 101 bool ans = isValidSudoku(v1); 102 cout <<ans << endl; 103 //cout << endl; 104 return 0; 105 }
以上是关于LeetCode 1. 10 有效的数独的主要内容,如果未能解决你的问题,请参考以下文章