1. 程式人生 > 其它 >網易互娛23屆實習筆試_3x3鋸齒數獨

網易互娛23屆實習筆試_3x3鋸齒數獨

一、輸入:

輸入一個3x3數獨,字元'.'代表空
輸入三個宮的域,每個宮包括三個位置,[0,0]表示0行0列

二、輸出要求:

1.每個宮裡最終123各出現一次,

2.數獨中的行列裡不出現重複字元;

 

輸出滿足條件的解

思想:先根據輸入找到所有行列不重複的數獨,再判斷三個宮是否滿足不重複;

  1 #include <iostream>
  2 #include <bits/stdc++.h>
  3 using namespace std;
  4 int a[3][3];//儲存三個宮區域
  5 int cnt;//記錄滿足的個數
  6 bool isValid(int row, int
col, char val, vector<vector<char>>& board) { 7 for (int i = 0; i < 3; i++) { // 判斷行裡是否重複 8 if (board[row][i] == val) { 9 return false; 10 } 11 } 12 for (int j = 0; j < 3; j++) { // 判斷列裡是否重複 13 if (board[j][col] == val) { 14 return
false; 15 } 16 } 17 return true; 18 } 19 bool func(vector<vector<char>> board){ 20 for (int i = 0; i<3;i++){ //第i個宮 21 int vec[3]; 22 memset(vec,0,sizeof(vec)); 23 for (int j = 0; j < 3;j++){ 24 if (vec[board[a[i][j]/3][a[i][j]%3
]-'1']==1){ 25 return false; 26 cout <<"失敗"<< a[i][j] << endl; 27 } 28 vec[board[a[i][j] / 3][a[i][j] % 3]-'1'] = 1; 29 } 30 } 31 return true; 32 } 33 34 bool backtracking(vector<vector<char>>& board) { 35 int x, y; 36 for (int i = 0; i < board.size(); i++) { // 遍歷行 37 for (int j = 0; j < board[0].size(); j++) { // 遍歷列 38 x = i; 39 y = j; 40 if (board[i][j] != '.') continue; 41 for (char k = '1'; k <= '3'; k++) { // (i, j) 這個位置放k是否合適 42 if (isValid(i, j, k, board)) { 43 board[i][j] = k; // 放置k 44 if (backtracking(board)) { 45 return true; // 如果找到合2 適一組立刻返回 46 } 47 board[i][j] = '.'; // 回溯,撤銷k 48 } 49 } 50 return false; // 9個數都試完了,都不行,那麼就返回false 51 } 52 } 53 if(x==2&&y==2){ //判斷是否滿足宮 54 if(func(board)){ 55 cout << "cnt++:" << endl; 56 cnt++; 57 for(int i=0;i<3;i++){ 58 for(int j=0;j<3;j++){ 59 cout<<board[i][j]<<" "; 60 } 61 cout << endl; 62 } 63 } 64 /*for(int i=0;i<3;i++){ 65 for(int j=0;j<3;j++){ 66 cout<<board[i][j]<<" "; 67 } 68 cout << endl; 69 }*/ 70 } 71 return false; 72 //return true; // 遍歷完沒有返回false,說明找到了合適棋盤位置了 73 } 74 75 int main() { 76 cnt = 0; 77 vector<vector<char>>board={{0,0,0},{0,0,0},{0,0,0}}; 78 for(int i=0;i<3;i++){ 79 for(int j=0;j<3;j++){ 80 char ch; 81 cin>>ch; 82 board[i][j]=ch; 83 //cout<<ch<<endl; 84 } 85 } 86 int x, y; 87 for (int i = 0; i < 3;i++){ 88 for (int j = 0; j < 3;j++){ 89 cin >> x >> y; 90 a[i][j] = 3 * x + y; 91 //cout << 3 * x + y; 92 } 93 } 94 cout << endl; 95 cout << "x" << endl; 96 backtracking(board); 97 int coun = cnt; 98 cout << "answer " << cnt << endl; 99 return 0; 100 }

測例1:

輸入

..3 ... ...
0 0 1 0 1 1
0 1 0 2 1 2
2 0 2 1 2 2

 

 

輸出:

cnt++:
1 2 3
2 3 1
3 1 2
cnt++:
2 1 3
1 3 2
3 2 1
answer 2