POJ2676 DFS+剪枝

Sudoku
Time Limit: 2000MS   Memory Limit: 65536K
Total Submissions: 22411   Accepted: 10576   Special Judge

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

DFS+剪枝, 暴力DFS会wa

//DFS+剪枝
#include <iostream>
#include <cstdio>
#include <set>
#include <queue>
#include <algorithm>
#include <stack>
#include <map>
#include <cstring>
using namespace std;
typedef long long ll;
int G[10][10];
int vis_row[10][10];
int vis_col[10][10];
int vis_block[10][10];
bool dfs(int x, int y) {
	if (x == 10) return true;
	bool flag = false;
	if (G[x][y] != 0) {
		if (y == 9) flag = dfs(x + 1, 1);
		else flag = dfs(x, y + 1);
		if (flag) return true;
		else return false;
	} else {
		int k = 3*((x-1)/3)+(y-1)/3+1;
		for (int i = 1; i <= 9; i++) {
			if (!vis_row[x][i] && !vis_col[y][i] && !vis_block[k][i]) {
				G[x][y] = i;
				vis_row[x][i] = 1;
				vis_col[y][i] = 1;
				vis_block[k][i] = 1;
				if (y == 9) flag = dfs(x + 1, 1);
				else flag = dfs(x, y + 1);
				if (!flag) {
					G[x][y] = 0;
					vis_row[x][i] = 0;
					vis_col[y][i] = 0;
					vis_block[k][i] = 0;
				} else {
					return true;
				}
			}
		}
	}
	return false;
}
int main() {
	int t;
	cin >> t;
	while (t-- != 0) {
		char b[10][10];
		memset(vis_row, 0, sizeof(vis_row));
		memset(vis_col, 0, sizeof(vis_col));
		memset(vis_block, 0, sizeof(vis_block));
		for (int i = 1; i <= 9; i++) {
			for (int j = 1; j <= 9; j++) {
				cin >> b[i][j];
				G[i][j] = b[i][j] - '0';
				if (G[i][j] != 0) {
					int k = 3*((i-1)/3)+(j-1)/3+1;
					vis_row[i][G[i][j]] = 1;
					vis_col[j][G[i][j]] = 1;
					vis_block[k][G[i][j]] = 1;
				}
			}
		}
		dfs(1, 1);
		for (int i = 1; i <= 9; i++) {
			for (int j = 1; j <= 9; j++) {
				cout << G[i][j];
			}
			cout << endl;
		}
	}



	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_34649947/article/details/79973044