#include<iostream>
using namespace std;
int map[9][9] =
{
0, 0, 5, 3, 0, 0, 0, 0, 0,
8, 0, 0, 0, 0, 0, 0, 2, 0,
0, 7, 0, 0, 1, 0, 5, 0, 0,
4, 0, 0, 0, 0, 5, 3, 0, 0,
0, 1, 0, 0, 7, 0, 0, 0, 6,
0, 0, 3, 2, 0, 0, 0, 8, 0,
0, 6, 0, 5, 0, 0, 0, 0, 9,
0, 0, 4, 0, 0, 0, 0, 3, 0,
0, 0, 0, 0, 0, 9, 7, 0, 0
};
bool store[3][9][9];
int spa(int i, int j) {//给出一个坐标,判断出在第几个区域
return i / 3 * 3 + j / 3;
}
int check(int num, int x, int y) //横,竖,块中都不存在
{
if (!store[0][x][num] && !store[1][y][num] && !store[2][spa(x,y)][num])
{
return 1;
}
return 0;
}
void show() //打印
{
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
printf("%3d", map[i][j]);
}
printf("\n");
}
printf("\n---------------------------\n");
}
void dfs(int x, int y)
{
if (y >= 9) { x++;y = 0;} //到达一行末尾,移动到下一行
if (x >=9) { show(); return; }
while ( y<9 && map[x][y]!=0 ) //找到下一个可以填写的点
{
y++;
}
if (y == 9) //
{
dfs(x + 1, 0);
return;
}
for (int i = 0; i < 9; i++)
{
if (check(i, x, y))
{
//回溯算法
map[x][y] = i+1;
store[0][x][i] = 1;
store[1][y][i] = 1;
store[2][spa(x, y)][i] = 1;
dfs(x,y+1);
map[x][y] =0;
store[0][x][i] =0;
store[1][y][i] =0;
store[2][spa(x, y)][i] =0;
}
}
}
void main()
{
//请0
memset(store, 0, sizeof(store));
//初始化
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
if (map[i][j])
{
store[0][i][map[i][j] - 1] = 1;
store[1][j][map[i][j] - 1] = 1;
store[2][spa(i,j)][map[i][j] - 1] = 1;
}
}
}
//
dfs(0, 0);
system("pause");
}
using namespace std;
int map[9][9] =
{
0, 0, 5, 3, 0, 0, 0, 0, 0,
8, 0, 0, 0, 0, 0, 0, 2, 0,
0, 7, 0, 0, 1, 0, 5, 0, 0,
4, 0, 0, 0, 0, 5, 3, 0, 0,
0, 1, 0, 0, 7, 0, 0, 0, 6,
0, 0, 3, 2, 0, 0, 0, 8, 0,
0, 6, 0, 5, 0, 0, 0, 0, 9,
0, 0, 4, 0, 0, 0, 0, 3, 0,
0, 0, 0, 0, 0, 9, 7, 0, 0
};
bool store[3][9][9];
int spa(int i, int j) {//给出一个坐标,判断出在第几个区域
return i / 3 * 3 + j / 3;
}
int check(int num, int x, int y) //横,竖,块中都不存在
{
if (!store[0][x][num] && !store[1][y][num] && !store[2][spa(x,y)][num])
{
return 1;
}
return 0;
}
void show() //打印
{
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
printf("%3d", map[i][j]);
}
printf("\n");
}
printf("\n---------------------------\n");
}
void dfs(int x, int y)
{
if (y >= 9) { x++;y = 0;} //到达一行末尾,移动到下一行
if (x >=9) { show(); return; }
while ( y<9 && map[x][y]!=0 ) //找到下一个可以填写的点
{
y++;
}
if (y == 9) //
{
dfs(x + 1, 0);
return;
}
for (int i = 0; i < 9; i++)
{
if (check(i, x, y))
{
//回溯算法
map[x][y] = i+1;
store[0][x][i] = 1;
store[1][y][i] = 1;
store[2][spa(x, y)][i] = 1;
dfs(x,y+1);
map[x][y] =0;
store[0][x][i] =0;
store[1][y][i] =0;
store[2][spa(x, y)][i] =0;
}
}
}
void main()
{
//请0
memset(store, 0, sizeof(store));
//初始化
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
if (map[i][j])
{
store[0][i][map[i][j] - 1] = 1;
store[1][j][map[i][j] - 1] = 1;
store[2][spa(i,j)][map[i][j] - 1] = 1;
}
}
}
//
dfs(0, 0);
system("pause");
}