http://poj.org/problem?id=3984
深度搜索是搜索算法中的一类重要的思想。他的过程是从起点开始,找到其邻接点并标记,然后尽量深入。最后在返回这个前驱点进行搜索。
这道题是深度搜索中的基础题,要注意对其剪枝:1.搜索过的点不重复 2.用一个结构体数组记录他的结构,便于最后的输出。
#include<iostream>
#include<cstdio>
#include<cmath>
#define INF 0x3f3f
using namespace std;
int map[5][5];
bool visited[5][5];
int movex[4] = { 1, 0, -1, 0 };
int movey[4] = { 0, 1, 0, -1 };
struct point
{
int x, y;
}back[5][5];
int dfs(int a, int b)
{
int temp = INF,temp1;
visited[a][b] = true;
int i, j;
if (a == 4 && b == 4)return 0;
for (i = 0; i < 4; i++)
{
if (a + movex[i] >= 0 && a + movex[i] < 5 && b + movey[i] >= 0 && b + movey[i] < 5)
{
if (!visited[a + movex[i]][b + movey[i]] && map[a + movex[i]][b + movey[i]] == 0)
{
temp1 = dfs(a + movex[i], b + movey[i]);
if (temp1 < temp)
{
temp =temp1 + 1;
back[a][b].x = a + movex[i];
back[a][b].y = b + movey[i];
}
}
}
if (visited[4][4])return temp;
}
visited[a][b] = false;
return temp;
}
int main()
{
memset(visited, false, sizeof(visited));
visited[0][0] = true;
int i, j,temp;
int temp1, temp2;
temp = INF;
for (i = 0; i < 5; i++)
for (j = 0; j < 5; j++)
cin >> map[i][j];
for (i = 0; i < 4; i++)
{
if (movex[i] >= 0 && movey[i] >= 0)
{
if (map[movex[i]][movey[i]]==0&&temp>dfs(movex[i], movey[i]))
{
temp=dfs(movex[i], movey[i]);
back[0][0].x = movex[i];
back[0][0].y = movey[i];
}
}
}
i = j = 0;
while (1)
{
printf("(%d, %d)\n", i, j);
temp1 = back[i][j].x;
temp2 = back[i][j].y;
if (temp1 == 4 && temp2 == 4)break;
i = temp1; j = temp2;
}
printf("(4, 4)\n");
system("pause");
return 0;
}