数独检测器:帝国理工C++作业
#include <fstream> #include <vector> #include <iostream> #include <string> using namespace std; bool check_sudoku(const vector<int>& input); int coordtoidx(int row, int col); void extract_row(const vector<int>& input, int row, vector<int>& output); void extract_col(const vector<int>& input, int col, vector<int>& output); void extract_subsquare(const vector<int>& input, int row, int col, vector<int>& output); bool once(int num,const vector<int>& input); int main() { ifstream infile; cout<<"Please input a input file name"<<endl; string infilename; cin>>infilename; infile.open(infilename); if (!infile.is_open()) { cout<<"could not open input file"<<endl; system("pause"); exit(EXIT_FAILURE); } vector<int> input; int number; while (infile>>number) { input.push_back(number); } infile.close(); bool isOK=check_sudoku(input); if (isOK) { cout<<"valid"<<endl; } else { cout<<"invalid"<<endl; } system("pause"); return 0; } bool check_sudoku(const vector<int>& input) { for (int i=0; i<9; i++) { vector<int> rowNumbers; extract_row(input,i,rowNumbers); for (int m=1;m<10;m++) { bool onceFlag=once(m,rowNumbers); if(!onceFlag) { return false; } } } for (int j=0; j<9; j++) { vector<int> colNumbers; extract_col(input,j,colNumbers); for (int m=1;m<10;m++) { bool onceFlag=once(m,colNumbers); if(!onceFlag) { return false; } } } for (int p=0; p<9; p=p+3) for (int q=0; q<9; q=q+3) { vector<int> subsquareNumbers; extract_subsquare(input,p,q,subsquareNumbers); for (int m=1;m<10;m++) { bool onceFlag=once(m,subsquareNumbers); if(!onceFlag) { return false; } } } return true; } int coordtoidx(int row, int col) { return row*9+col; } void extract_row(const vector<int>& input, int row, vector<int>& output) { for (int c=0; c<9;c++) { int idx=coordtoidx(row,c); output.push_back(input.at(idx)); } } void extract_col(const vector<int>& input, int col, vector<int>& output) { for (int r=0; r<9;r++) { int idx=coordtoidx(r,col); output.push_back(input.at(idx)); } } void extract_subsquare(const vector<int>& input, int row, int col, vector<int>& output) { for (int r=row; r<row+3;r++) for (int c=col; c<col+3;c++) { int idx=coordtoidx(r,c); output.push_back(input.at(idx)); } } bool once(int num, const vector<int>& input) { int count=0; for (unsigned int i=0; i<input.size(); i++) { if (input.at(i)==num) { count++; } } return count==1?true:false; }