#include <bits/stdc++.h>
using namespace std;
struct consult_row_0 {
int row, num_0;
};
struct consult_row_0 dic_row_0[10];
int origin[10][10];
bool row[10][10], column[10][10], box[10][10];
int point_reach[100][3];//x,y,box
int point_counter;
int consult_box(int x, int y)
{
return (x - 1) / 3 * 3 + (y - 1) / 3 + 1;
}
void dfs(int point_num_reach)
{
if (point_num_reach == point_counter)
{
cout << endl;
for (int i = 1; i <= 9; i++)
{
for (int j = 1; j <= 9; j++)
{
cout << origin[i][j] << " ";
}
cout << endl;
}
return;
}
for (int i = 1; i <= 9; i++)
{
if (row[point_reach[point_num_reach][0]][i] == false && column[point_reach[point_num_reach][1]][i] == false && box[point_reach[point_num_reach][2]][i] == false)
{
row[point_reach[point_num_reach][0]][i] = column[point_reach[point_num_reach][1]][i] = box[point_reach[point_num_reach][2]][i] = true;
origin[point_reach[point_num_reach][0]][point_reach[point_num_reach][1]] = i;
dfs(point_num_reach + 1);
row[point_reach[point_num_reach][0]][i] = column[point_reach[point_num_reach][1]][i] = box[point_reach[point_num_reach][2]][i] = false;
origin[point_reach[point_num_reach][0]][point_reach[point_num_reach][1]] = 0;
}
}
}
bool cmp(consult_row_0 a, consult_row_0 b)
{
return a.num_0 < b.num_0;
}
int main()
{
for (int i = 1; i <= 9; i++)
{
dic_row_0[i].row = i;
}
for (int i = 1; i <= 9; i++)
{
for (int j = 1; j <= 9; j++)
{
cin >> origin[i][j];
if (origin[i][j] > 0)
{
row[i][origin[i][j]] = column[j][origin[i][j]] = box[consult_box(i, j)][origin[i][j]] = true;
}
else
{
dic_row_0[i].num_0++;
}
}
}
sort(dic_row_0 + 1, dic_row_0 + 10, cmp);
for (int i = 1; i <= 9; i++)
{
for (int j = 1; j <= 9; j++)
{
if (origin[dic_row_0[i].row][j] == 0)
{
point_reach[point_counter][0] = dic_row_0[i].row;
point_reach[point_counter][1] = j;
point_reach[point_counter][2] = consult_box(dic_row_0[i].row, j);
point_counter++;
}
}
}
dfs(0);
return 0;
}
数独
最新推荐文章于 2021-05-13 21:56:26 发布