K - 迷宫问题 //bfs 和 dfs 结合

K - 迷宫问题


Description

定义一个二维数组:  
int maze[5][5] = {

	0, 1, 0, 0, 0,

	0, 1, 0, 1, 0,

	0, 0, 0, 0, 0,

	0, 1, 1, 1, 0,

	0, 0, 0, 1, 0,

};

它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。

Input

一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。

Output

左上角到右下角的最短路径,格式如样例所示。

Sample Input

0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0

Sample Output

(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4)

思路:这道题目非常简单,就是找出从(0,0)到(4,4)的最短路径,最短路径用bfs来求就可以了,难点在于把最短路径输出出来,这就需要dfs的回溯过程。

用bfs找到最短路径之后,v数组存放的这个路径中每一个点的前一个点的坐标,这样方便回溯的时候,把各个点输出

例如:

扫描二维码关注公众号,回复: 1108576 查看本文章

当前的点 1,0 2,0 2,1 2,2 2,3 2,4 3,4 4,4
存放的上一个点 0,0 1,0 2,0 2,1 2,2 2,3 2,4 3,4

回溯的时候就从

4,4    
3,4
2,4
2,3
2,2
2,1
2,0
1,0
0,0  dfs到最低端之后,就开始回溯从0,0 开始向上输出


DFS的特点:先从最开始搜到了最底层,然后再一层一层的返回输出。

这样dfs和bfs结合,利用bfs来把最优的路径找到,利用dfs的回溯把最优的路径输出;dfs和bfs结合对于这个题目来说:完美!


AC代码

#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string.h>
#include<queue>
#include<stdlib.h>
#include<math.h>
using namespace std;
struct node
{
    int x;
    int y;
}v[10][10];
int mp[10][10];
int vis[10][10];
int step[10][10];
int dir[4][2]={0,1,1,0,0,-1,-1,0};
queue<node>Q;
void dfs(int x,int y)
{
    if(x==0 && y==0)
    {
        return ;
    }
    dfs(v[x][y].x,v[x][y].y);
    printf("(%d, %d)\n",v[x][y].x,v[x][y].y);
} 
void bfs(int a,int b)
{
    node last,now;
    last.x=a;
    last.y=b;
    Q.push(last);
    while(!Q.empty())
    {
        last=Q.front();
        Q.pop();
        if(last.x==4 && last.y==4)
        {
            dfs(last.x,last.y);
            printf("(%d, %d)\n",last.x,last.y);
            return ;
        }
        for(int i=0;i<4;i++)
        {
            now.x=last.x+dir[i][0];
            now.y=last.y+dir[i][1];
            if(now.x>=0&&now.x<=5&&now.y>=0&&now.y<=5&&mp[now.x][now.y]!=1&&vis[now.x][now.y]==0)
            {
                v[now.x][now.y].x=last.x;
                v[now.x][now.y].y=last.y;
                vis[now.x][now.y]=1;
                Q.push(now);
            }
        }
    }
}
int main()
{
    for(int i=0;i<5;i++)
    {
        for(int j=0;j<5;j++)
        {
            scanf("%d",&mp[i][j]);
        }
    }
    bfs(0,0);
    return 0;
}



猜你喜欢

转载自blog.csdn.net/lmengi000/article/details/80426511