您的位置:首页 > 其它

【搜索】BFS、DFS的综合练习(小鼠迷宫)

2014-02-21 16:21 375 查看


分析:利用bfs可以计算出最短路径的距离len(即移动次数),然后用dfs计算出等于len(移动次数)时有多少种不同的最短路径。

#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
using namespace std;

#define N 100

int mark

, map

;
struct node{
int x, y;
int step;
};
int n, m, k;
int min_step;
int num;
int x1, x2, y1, y2;
int dir[4][2] = { 0, 1, 0, -1, 1, 0, -1, 0 }; //direction 控制方向

int BFS()
{
int x, y;
queue<node> q;
node cur, next;
cur.x = x1;
cur.y = y1;
cur.step = 0;
q.push(cur);
mark[x1][y1] = 1;
while( !q.empty() )
{
cur = q.front();
q.pop();
if(cur.x == x2 && cur.y == y2)
//如果找到,则肯定是一个找到的,故是最短路径
{
return cur.step;
}
for(int i = 0; i < 4; i++)
{
//进行方向的改变
next.x = x = cur.x + dir[i][0];
next.y = y = cur.y + dir[i][1];

if(x >= 1 && x <= n && y > 1 && y <= m && mark[x][y] == 0)
//判断行进之后是否符合条件
{
next.step = cur.step + 1;
q.push(next);
mark[x][y] = 1;
}
}
}
return -1;
}

void DFS(int x, int y, int c_step)
{
if(x == x2 && y == y2 && c_step == min_step)
{
num++;
return;
}
if( (x > x2? x - x2: x2 - x) + (y > y2? y - y2: y2 - y) + c_step > min_step )
//剪枝,如果这枝最优解都比最短路径长,则砍断
{
return;
}
for(int i = 0; i < 4; i++)
{
int xx, yy;
xx = x + dir[i][0];
yy = y + dir[i][1];
if(xx >= 1 && xx <= n && yy >= 1 && yy <= m && map[xx][yy] == 0)
{
map[xx][yy] = 1;
DFS(xx, yy, c_step + 1);
map[xx][yy] = 0;
}
}
}

int main()
{
cin >> n >> m >> k;
memset(map, 0, sizeof(map));
memset(mark, 0, sizeof(mark));
for(int i = 0; i < k; i++)
{
int a, b;
cin >> a >> b;
map[a][b] = 1;
mark[a][b] = 1;
}
cin >> x1 >> y1;
cin >> x2 >> y2;
min_step = -1;
min_step = BFS();

if(min_step == -1)
{
cout << "No Solution!" << endl;
}
else
{
num = 0;
DFS(x1, y1, 0);
cout << min_step << endl;
cout << num << endl;
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: