| ||||||||||
| Online Judge | Problem Set | Authors | Online Contests | User | ||||||
|---|---|---|---|---|---|---|---|---|---|---|
| Web Board Home Page F.A.Qs Statistical Charts | Current Contest Past Contests Scheduled Contests Award Contest | |||||||||
第一道自己写出来的dfs题,虽然时间有点长,但是AC了,思路比较简单#include<iostream>
using namespace std;
int map[11][11];
int flag;
bool checkR_C(int c, int r,int tar)
{
for (int i = 1; i <= 9; i++)
if (map[c][i] == tar)
return false;
for (int j = 1; j <= 9; j++)
if (map[j][r] == tar)
return false;
return true;
}
bool checkSS(int c, int r, int tar)
{
int x, y;
if (c >= 1 && c <= 3)
x = 1;
else if (c >= 4 && c <= 6)
x = 4;
else if (c >= 7 && c <= 9)
x = 7;
if (r >= 1 && r <= 3)
y = 1;
else if (r >= 4 && r <= 6)
y = 4;
else if (r >= 7 && r <= 9)
y = 7;
for (int i = x; i <= x + 2; i++)
for (int j = y; j <= y + 2; j++)
if (map[i][j] == tar)
return false;
return true;
}
void dfs(int x, int y,int last)
{
if (x == 10)
{
for (int i = 1; i <= 9; i++)
{
for (int j = 1; j <= 9; j++)
cout << map[i][j];
cout << endl;
}
flag = 1;
return;
}
if (flag)
return;
if (map[x][y] == 0)
{
for (int i = 1; i <= 9; i++)
{
if (checkR_C(x, y, i) && checkSS(x, y, i)&&!flag)
{
map[x][y] = i;
if (y == 9)
dfs(x + 1, 1, last-1);
else
dfs(x, y + 1, last-1);
map[x][y] = 0;
}
}
}
else if (map[x][y] != 0)
{
if (y == 9)
dfs(x + 1, 1, last);
else
dfs(x, y + 1, last);
}
}
int main()
{
int n;
cin >> n;
while (n--)
{
flag = 0;
int sum = 0;
for (int i = 1; i <= 9; i++)
for (int j = 1; j <= 9; j++)
{
char c;
cin >> c;
map[i][j] = c - '0';
if (map[i][j] != 0)
{
sum++;
}
}
dfs(1, 1, 81 - sum);
}
system("pause");
return 0;
}
Followed by: Post your reply here: |
All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator