POJ2676数独游戏题解

第三次才AC我好菜

一道“简单”的问题。

Description

Sudoku is a very simple task. A square table with 9 rows and 9 columns is divided to 9 smaller squares 3x3 as shown on the Figure. In some of the cells are written decimal digits from 1 to 9. The other cells are empty. The goal is to fill the empty cells with decimal digits from 1 to 9, one digit per cell, in such way that in each row, in each column and in each marked 3x3 subsquare, all the digits from 1 to 9 to appear. Write a program to solve a given Sudoku-task.

Input

The input data will start with the number of the test cases. For each test case, 9 lines follow, corresponding to the rows of the table. On each line a string of exactly 9 decimal digits is given, corresponding to the cells in this line. If a cell is empty it is represented by 0.

Output

For each test case your program should print the solution in the same format as the input data. The empty cells have to be filled according to the rules. If solutions is not unique, then the program may print any one of them.

Sample Input

1
103000509
002109400
000704000
300502006
060000050
700803004
000401000
009205800
804000107

Sample Output

143628579
572139468
986754231
391542786
468917352
725863914
237481695
619275843
854396127

简单来讲就是给T个数独给我们,让我们求解。

思路

根其他深搜一样还是要有变量来存每一行,每一列,每一宫(每一个大格)
是否有数字一到九。
剩下的代码就很好写,只是长了一点。
最后附上求宫公式,点想(x,y)在第:

3 * ((i - 1) / 3) + (j - 1) / 3 + 1

宫。
POJ2676数独游戏题解_第1张图片

AC代码

#include 
#include 

using namespace std;

int a[15][15];
int row[100][100], col[100][100], gird[100][100];

bool dfs(int x, int y) {
	if (x == 10) return 1;
	bool flag = 0;
	cout << 1; //防抄袭
	if (a[x][y]) {
		if (y == 9)  {
			flag = dfs(x + 1, 1);
		} else {
			flag = dfs(x, y + 1);
		}
		return flag?1:0;
	} else {
		int k = 3 * ((x - 1) / 3) + 1 + ((y - 1) / 3); 
		for (int i = 1; i <= 9; i++) {
			if (!row[x][i] && !col[y][i] && !gird[k][i]) {
				a[x][y] = i;
				row[x][i] = 1;
				col[y][i] = 1;
				gird[k][i] = 1;
				if (y == 9) {
					flag = dfs(x + 1, 1);
				} else {
					flag = dfs(x, y + 1);
				}
				if (!flag) {
					a[x][y] = 0;
					row[x][i] = 0;
					col[y][i] = 0;
					gird[k][i] = 0;
				} else return 1; 
			}
		}
	}
	return 0;
}

int main() {
	int T;
	cin >> T;
	while (T--) {
		memset(row, 0, sizeof(row));
		memset(col, 0, sizeof(col));
		memset(gird, 0, sizeof(gird));
		for (int i = 1; i <= 9; i++) {
			for (int j = 1; j <= 9; j++) {
				char tmp;
				cin >> tmp;  //用scanf("%1d", &a[i][j]) 也可以(邪门方法 )
				a[i][j] = tmp - '0';
				if (a[i][j]) {
					int k = 3 * ((i - 1) / 3) + (j - 1) / 3 + 1;
					row[i][a[i][j]] = 1;
					col[j][a[i][j]] = 1;
					gird[k][a[i][j]] = 1;
				}
			}
		}
		dfs(1, 1);
		for (int i = 1; i <= 9; i++) {
			for (int j = 1; j <= 9; j++) {
				cout << a[i][j];
			}
			cout << endl;
		}
		cout << endl;
	}
	return 0; //华丽结束
}

你可能感兴趣的:(深度优先搜索,模拟,深度优先,算法,剪枝)