Poj2676

经典DFS现在看来nice啊!

 package SoduKu;

 import java.io.InputStreamReader;
import java.util.Scanner;
/*
*我用row[k][i]表示第k行是否已经有数i
*col[k][i]表示第k列是否已经有数i
*而sq[k][i]表示第k个九宫格是否有数i(这里k=(x/3)*3+(y/3),可以想想为什么)
*从0,0 依次搜到8,8 DFS依次往下
**/
public class Poj2676{ static int[][] map = new int[9][9];
static int[][] col = new int[9][9];
static int[][] row = new int[9][9];
static int[][] sq = new int[9][9];
static boolean isFind = false;
static void fill(int[][] a){
for(int i = 0; i < 9; ++i){
for(int j = 0; j < 9; ++j)
a[i][j] = 0;
}
}
static void print(){
for(int i = 0; i < 9; ++i) {
for(int j = 0; j < 9; ++j){
System.out.print(map[i][j]+1);
}
System.out.println();
}
} static void dfs(int x, int y){
int u = x*9 + y + 1;
if(x == 9){
isFind = true;
print();
} if(isFind)
return;
if(map[x][y] != -1){
dfs(u/9, u%9);
return;
} for(int i = 0; i < 9 && !isFind; ++i){
int k = (x/3)*3 + y/3;
if(row[x][i] == 0 && col[y][i] == 0 && sq[k][i] == 0){
row[x][i] = col[y][i] = sq[k][i] = 1;
map[x][y] = i; dfs(u/9, u%9); row[x][i] = col[y][i] = sq[k][i] = 0;
map[x][y] = -1;
}
}
}
public static void main(String[] args){
Scanner scanner = new Scanner(new InputStreamReader(System.in)); int k;
int n = scanner.nextInt();
scanner.nextLine();
for(int ni = 1; ni <= n; ++ni){ fill(map);
fill(row);
fill(col);
fill(sq);
isFind = false;
for(int i = 0; i < 9; ++i){
String string = scanner.nextLine();
for(int j = 0; j < 9; ++j) {
k = string.charAt(j) - '0';
map[i][j] = k-1;
if(k != 0){
row[i][k-1] = col[j][k-1] = sq[(i/3)*3 + (j/3)][k-1] = 1;
}
}
}
dfs(0, 0);
}
}
}
上一篇:BZOJ 3747 POI2015 Kinoman


下一篇:TLS 1.3 VS TLS 1.2,让你明白 TLS 1.3 的强大