概述:数独游戏,给你一个数独游戏盘,让你求解
思路:把数字1-9填写到空格当中,并且使方格的每一行和每一列中都包含1-9这九个数字。同时还要保证,空格中用粗线划分成9个3x3的方格也同时包含1-9这九个数字。这样的话,很容易就联想到DFS搜索,所以,我们采取搜索,遇到“?”就尝试求解。
感想:不是很难- =
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std;
const int MAX = 10;
char Map[MAX][MAX];
int pos[MAX * 9][2];
bool row[MAX][MAX], list[MAX][MAX];
int k;
bool check(int v, int num)
{
int n = pos[v][0] / 3 * 3;
int m = pos[v][1] / 3 * 3;
for (int i = n; i<n + 3; ++i)
{
for (int j = m; j<m + 3; ++j)
{
if (Map[i][j] == num + '0')return false;
}
}
return true;
}
bool DFS(int v) {
if (v == k) { return true; }//代表前面已经把所有的点都搜索完了.
for (int i = 1; i<10; ++i) {
if (!row[pos[v][0]][i] && !list[pos[v][1]][i] && check(v, i)) {
Map[pos[v][0]][pos[v][1]] = i + '0';
row[pos[v][0]][i] = true;
list[pos[v][1]][i] = true;
if (DFS(v + 1)) { return true; }
Map[pos[v][0]][pos[v][1]] = '?';
row[pos[v][0]][i] = false;
list[pos[v][1]][i] = false;
}
}
return false;
}
void output() {
for (int i = 0; i<9; ++i) {
cout << Map[i][0];
for (int j = 1; j<9; ++j) {
cout << ' ' << Map[i][j];
}
cout << endl;
}
return;
}
int main() {
int num = 0;
while (1) {
k = 0;
memset(row, false, sizeof row);
memset(list, false, sizeof list);
for (int i = 0; i<9; ++i) {
for (int j = 0; j<9; ++j) {
if (!(cin >> Map[i][j]))exit(0);
if (Map[i][j] == '?') { pos[k][0] = i; pos[k++][1] = j; continue; }
row[i][Map[i][j] - '0'] = true;
list[j][Map[i][j] - '0'] = true;
}
}
DFS(0);//开始搜索第1个是问号的点.
if (num++)cout << endl;
output();
}
return 0;
}
747

被折叠的 条评论
为什么被折叠?



