#13188: C++ 解答(運用STL) 歡迎參考


pppoooppp654852 (C8763)

學校 : 高雄市立高雄高級工業職業學校
編號 : 66796
來源 : [75.164.136.19]
最後登入時間 :
2018-02-21 09:25:18
a016. 數獨(SUDOKU) | From: [97.120.28.242] | 發表日期 : 2017-12-31 06:32

#include <iostream>
#include <string>
#include <vector>
#include <set>

using namespace std;


bool check_row_column(vector<vector<int>> const &vec) {
//check the row if they have the same numbers
for (int i = 0; i < vec.size(); ++i) {
set<int> iset;
for (int j = 0; j < vec[i].size(); ++j) {
if (iset.count(vec[i][j]) == 0)
iset.insert(vec[i][j]);
else
return false;
}
}

//check the column if they have the same numbers
for (int i = 0; i < vec[0].size(); ++i) {
set<int> iset;
for (int j = 0; j < vec.size(); ++j) {
if (iset.count(vec[j][i]) == 0)
iset.insert(vec[j][i]);
else
return false;
}
}
return true;
}
bool check_3by3(vector<vector<int>> const &vec) {
for (int i = 0; i < 9; i += 3) {
for (int j = 0; j < 9; j += 3) {
set<int> iset;
//check the 3 * 3 square if they have the same numbers
for (int k = 0; k < 3; ++k) {
for (int l = 0; l < 3; ++l) {
if (iset.count(vec[i + k][j + l]) == 0)
iset.insert(vec[i + k][j + l]);
else
return false;
}
}
}
}
return true;
}
int main(int argc, char **argv)
{

int temp;
while (cin >> temp) {
vector<vector<int>> vec;
for (int i = 0; i < 9; ++i) {
vector<int> ivec;
vec.push_back(ivec);
for (int j = 0; j < 9; ++j) {
if (i == 0 && j == 0)
vec[0].push_back(temp);
else {
cin >> temp;
vec[i].push_back(temp);
}
}
}

if (check_3by3(vec) && check_row_column(vec))
cout << "yes" << endl;
else
cout << "no" << endl;
}
}

 

陣列的話我是用vector

因為已經用習慣了

中間的檢查部分用set來檢查是否有重複的部分

 
ZeroJudge Forum