POJ-2676 Sudoku(DFS)
2016-08-16 21:01
281 查看
题目链接:点击打开链接
题意:
完成一个数独游戏。
思路:
DFS暴力搜索,设置三个标记数组, 分别标记第i行的9个数,第j行的9的数,第k个方格的九个数有没有出现过。
代码:
#include<iostream>
#include <string.h>
using namespace std;
int map[10][10];
bool row[10][10];
bool col[10][10];
bool grid[10][10];
bool flag = false;
void DFS(int x,int y)
{
if(flag)
return;
if(x==10)
{
flag = true;
return;
}
if(map[x][y])
{
if(y==9)
DFS(x+1,1);
else
DFS(x,y+1);
}
else
{
int k=3*((x-1)/3)+(y-1)/3+1;
for(int i=1;i<=9;i++)
if(!row[x][i] && !col[y][i] && !grid[k][i])
{
map[x][y]=i;
row[x][i]=true;
col[y][i]=true;
grid[k][i]=true;
if(y==9)
DFS(x+1,1);
else
DFS(x,y+1);
if(!flag)
{
map[x][y]=0;
row[x][i]=false;
col[y][i]=false;
grid[k][i]=false;
}
}
}
}
int main()
{
int test, i, j;
cin>>test;
while(test--)
{
flag = false;
memset(row,false,sizeof(row));
memset(col,false,sizeof(col));
memset(grid,false,sizeof(grid));
char MAP[10][10];
for(i=1;i<=9;i++)
for(j=1;j<=9;j++)
{
cin>>MAP[i][j];
map[i][j]=MAP[i][j]-'0';
if(map[i][j])
{
int k=3*((i-1)/3)+(j-1)/3+1;
row[i][ map[i][j] ]=true;
col[j][ map[i][j] ]=true;
grid[k][ map[i][j] ]=true;
}
}
DFS(1,1);
for(i=1;i<=9;i++)
{
for(j=1;j<=9;j++)
cout<<map[i][j];
cout<<endl;
}
}
return 0;
}
题意:
完成一个数独游戏。
思路:
DFS暴力搜索,设置三个标记数组, 分别标记第i行的9个数,第j行的9的数,第k个方格的九个数有没有出现过。
代码:
#include<iostream>
#include <string.h>
using namespace std;
int map[10][10];
bool row[10][10];
bool col[10][10];
bool grid[10][10];
bool flag = false;
void DFS(int x,int y)
{
if(flag)
return;
if(x==10)
{
flag = true;
return;
}
if(map[x][y])
{
if(y==9)
DFS(x+1,1);
else
DFS(x,y+1);
}
else
{
int k=3*((x-1)/3)+(y-1)/3+1;
for(int i=1;i<=9;i++)
if(!row[x][i] && !col[y][i] && !grid[k][i])
{
map[x][y]=i;
row[x][i]=true;
col[y][i]=true;
grid[k][i]=true;
if(y==9)
DFS(x+1,1);
else
DFS(x,y+1);
if(!flag)
{
map[x][y]=0;
row[x][i]=false;
col[y][i]=false;
grid[k][i]=false;
}
}
}
}
int main()
{
int test, i, j;
cin>>test;
while(test--)
{
flag = false;
memset(row,false,sizeof(row));
memset(col,false,sizeof(col));
memset(grid,false,sizeof(grid));
char MAP[10][10];
for(i=1;i<=9;i++)
for(j=1;j<=9;j++)
{
cin>>MAP[i][j];
map[i][j]=MAP[i][j]-'0';
if(map[i][j])
{
int k=3*((i-1)/3)+(j-1)/3+1;
row[i][ map[i][j] ]=true;
col[j][ map[i][j] ]=true;
grid[k][ map[i][j] ]=true;
}
}
DFS(1,1);
for(i=1;i<=9;i++)
{
for(j=1;j<=9;j++)
cout<<map[i][j];
cout<<endl;
}
}
return 0;
}
相关文章推荐
- poj-2676-Sudoku-dfs(其实就是爆搜。。)
- poj 2676 Sudoku(dfs填数)
- POJ 2676 Sudoku (数独 DFS)
- POJ_2676 Sudoku(DFS)
- POJ 2676 Sudoku 跳舞链 || dfs
- POJ 2676 Sudoku (DFS)
- poj 2676 Sudoku ( dfs )
- POJ 2676 Sudoku(DFS)
- poj_2676 Sudoku(dfs)
- poj 2676 sudoku dfs
- POJ 2676 Sudoku dfs
- poj 2676 Sudoku(dfs)
- POJ-2676-Sudoku-DFS
- poj 2676 sudoku ( 数独)----DFS
- POJ-2676 Sudoku (DFS)
- POJ 2676-Sudoku(DFS)
- POJ 2676 sudoku dfs
- POJ 2676-Sudoku(DFS-数独)
- poj dfs之2676 Sudoku
- [DFS]poj 2676 Sudoku 数独问题