题目链接:点击打开链接
题意:
完成一个数独游戏。
思路:
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; }