Sudoku POJ - 2676

Sudoku

 POJ - 2676 

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

题解+解析:

#include <iostream>
#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include <cstring>
#include <cmath>
#include <string>
#define INF 0x7f7f7f7f
typedef long long ll;
using namespace std;
int map[9][9];
bool squ[9][10];
bool row[9][10];
bool col[9][10];
bool flag;
void dfs(int x, int y)
{
	if (flag)//已经完成数独了,直接返回
	{
		return;
	}
	if (x == 9)//填完数独表,打印填好的数独表
	{
		flag = 1;
		for (int i = 0; i < 9; i++)
		{
			for (int j = 0; j < 9; j++)
			{
				printf("%d", map[i][j]);
			}
			printf("\n");
		}
		return;
	}
	if (map[x][y])//该位置有数字,填下一个位置
	{
		if (y == 8)
		{
			dfs(x+1, 0);
		}
		else
		{
			dfs(x, y+1);
		}
	}
	
	else//该位置没有数字,遍历可以填的数字
	{
		for (int m = 1; m <= 9; m++)
		{
			int k = 3*(x/3)+y/3;
			if (!row[x][m]&&!col[y][m]&&!squ[k][m])
			{
				map[x][y] = m;
				row[x][m] = true;//标记该行中该数字
				col[y][m] = true;//标记该列中该数字
				squ[k][m] = true;//标记该方块中该数字
				if (y == 8)//该行填完寻找下一行
				{
					dfs(x+1,0);
				}
				else//继续填改行的下一个数字
				{
					dfs(x,y+1);
				}
				map[x][y] = 0;//回溯
				row[x][m] = false;
				col[y][m] = false;
				squ[k][m] = false;
			}
		}
	}
}
int main()
{
	int t;
	scanf("%d",&t);
	getchar();
	while (t--)
	{
		memset(row,0,sizeof(row));//初始化
		memset(col,0,sizeof(col));
		memset(squ,0,sizeof(squ));
		flag = 0;
		for (int i = 0; i < 9; i++)//初始化数独表
		{
			for (int j = 0; j < 9; j++)
			{
				int temp;
				temp = getchar();
				map[i][j] = temp - '0';
				if (map[i][j])
				{
					int k = 3*(i/3)+j/3;//记录该位置是第几方块
					row[i][map[i][j]] = 1;//标记该行中该数字
					col[j][map[i][j]] = 1;//标记该列中该数字
					squ[k][map[i][j]] = 1;//标记该方块中该数字
				}
			}
			getchar();
		}
		dfs(0, 0);//从(0,0)处开始
	}
	return 0;
}


posted @ 2018-04-16 19:29  focus5679  阅读(85)  评论(0编辑  收藏  举报