本文主要是介绍TOJ 3287 Sudoku 9*9数独 dfs,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
描述
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.
输入
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.
输出
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.
样例输入
1
103000509
002109400
000704000
300502006
060000050
700803004
000401000
009205800
804000107
样例输出
143628579
572139468
986754231
391542786
468917352
725863914
237481695
619275843
854396127
题目来源
Southeastern Europe 2005
数独规则:横向,纵向,3*3的小方格里,1-9各出现一次。
题意:0的位置填补数,输出一种填法。3*(i/3)+j/3是计算在第几个小方格里。
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<iostream>
#include<string>
#include<algorithm>
#include<map>
#include<set>
#include<queue>
#include<vector>
using namespace std;
#define inf 0x3f3f3f3f
#define LL long long
int a[20][20],flag;
int r[20][20],l[20][20],s[20][20];//r行 l列 s小方阵
void dfs(int i,int j)
{if(i==9&&j==0)flag=1; else{if(a[i][j]!=0){if(j<8)dfs(i,j+1);elsedfs(i+1,0);}else{for(int k=1;k<=9;k++){if(!r[i][k]&&!l[j][k]&&!s[3*(i/3)+j/3][k]){a[i][j]=k;r[i][k]=1;l[j][k]=1;s[3*(i/3)+j/3][k]=1;if(j<8)dfs(i,j+1);elsedfs(i+1,0);if(flag)return;//回溯重置 a[i][j]=0;r[i][k]=0;l[j][k]=0;s[3*(i/3)+j/3][k]=0;}}}}
}
int main()
{int t,i,j;scanf("%d",&t);while(t--){memset(r,0,sizeof r);memset(l,0,sizeof l); memset(s,0,sizeof s);for(i=0;i<9;i++){for(j=0;j<9;j++){scanf("%1d",&a[i][j]);if(a[i][j]){r[i][a[i][j]]=1;l[j][a[i][j]]=1;s[3*(i/3)+j/3][a[i][j]]=1;}}}flag=0;dfs(0,0);for(i=0;i<9;i++){for(j=0;j<9;j++){printf("%d",a[i][j]);}printf("\n");}}
}
这篇关于TOJ 3287 Sudoku 9*9数独 dfs的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!