首页 > 新闻动态 >  

新闻动态
NEWS

POJ 2676 暴力深搜

添加时间:2013-8-6 点击量:

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 1 to 9. The other cells are empty. The goal is to fill the empty cells with decimal digits 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 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
<cstring>

using namespace std;

//column[][]默示第 i列数字 j是否用过,同row[][]
//grid[][]默示第 i个9X9的块内数字 j是否用过
bool flag;
bool column[10][10],row[10][10],grid[10][10];
int map[10][10];

void dfs(int x,int y)
{
if(flag)
return ;
if(x==10
{
flag
=true;
forint i=1;i<=9;i++
{
forint j=1;j<=9;j++
cout
<<map[i][j];
cout
<<endl;
}
return ;
}
if(map[x][y])
{
if(y==9
dfs(x
+11);
else
dfs(x,y
+1);
}
else
{
int n=(x-1)/33+(y-1)/3+1;
forint i=1;i<=9;i++
{
if(!column[y][i]&&!row[x][i]&&!grid[n][i])
{
column[y][i]
=true;
row[x][i]
=true;
grid[n][i]
=true;
map[x][y]
=i;
if(y==9
dfs(x
+11);
else
dfs(x,y
+1);
column[y][i]
=false;
row[x][i]
=false;
grid[n][i]
=false;
map[x][y]
=0;
}
}
}
}

int main()
{
int ncase;
cin
>>ncase;
while(ncase--
{
char ch[10][10];
memset(grid,
falsesizeof(grid));
memset(row,
falsesizeof(grid));
memset(column,
falsesizeof(column));
flag
=false;
forint i=1;i<=9;i++
{
forint j=1;j<=9;j++
{
cin
>>ch[i][j];
map[i][j]
=ch[i][j]-0;
if(map[i][j])
{
int n=(i-1)/33+(j-1)/3+1;
row[i][map[i][j]]
=true;
column[j][map[i][j]]
=true;
grid[n][map[i][j]]
=true;
}
}
}
dfs(
11);
}
return 0;
}


View Code

原来,再大的房子,再大的床,没有相爱的人陪伴,都只是冰冷的物质。而如果身边有爱人陪伴,即使房子小,床小,也觉得无关紧要,因为这些物质上面有了爱的温度,成了家的元素。—— 何珞《婚房》#书摘#
分享到: