6264:走出迷宫(DFS和BFS)

描述

当你站在一个迷宫里的时候,往往会被错综复杂的道路弄得失去方向感,如果你能得到迷宫地图,事情就会变得非常简单。
假设你已经得到了一个n*m的迷宫的图纸,请你找出从起点到出口的最短路。

输入
第一行是两个整数n和m(1<=n,m<=100),表示迷宫的行数和列数。
接下来n行,每行一个长为m的字符串,表示整个迷宫的布局。字符'.'表示空地,'#'表示墙,'S'表示起点,'T'表示出口。
输出
输出从起点到出口最少需要走的步数。
DFS
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <cctype>
#include <algorithm>

using namespace std;

int n,m,walk[200][200],sx,sy,ex,ey,ans=0x3f3f3f3f;
char s[200][200];

int row[4]={-1,0,1,0};
int col[4]={0,1,0,-1};

void DFS(int x,int y,int sum)
{
    if(x==ex&&y==ey)
    {
        if(sum<ans)
            ans=sum;
        return;
    }
    for(int i=0;i<=3;i++)
    {
        int xx=x+row[i];
        int yy=y+col[i];
        if(xx>=0&&xx<m&&yy>=0&&yy<n&&walk[xx][yy]>sum+1&&s[xx][yy]!='#')
        {
            walk[xx][yy]=sum+1;
            DFS(xx,yy,sum+1);
        }

    }
    return;
}
int main()
{
    cin>>m>>n;
    memset(walk,0x3f,sizeof(walk));
    for(int i=0;i<m;i++)
    {
        for(int j=0;j<n;j++)
        {
            cin>>s[i][j];
            if(s[i][j]=='S')
            {
                sx=i;sy=j;
            }
            if(s[i][j]=='T')
            {
                ex=i;ey=j;
            }
        }
    }
    walk[sx][sy]==0;
    DFS(sx,sy,0);
    cout<<ans<<endl;
    return 0;
}

 

BFS
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <queue>

using namespace std;

const int maxn=100;
struct node{
    int x,y;
    int step;
}S,T,Node;

int n,m;
char maze[maxn][maxn];
bool inq[maxn][maxn];
int X[4]={0,0,1,-1};
int Y[4]={1,-1,0,0};

bool test(int x,int y)
{
    if(x>=n||x<0||y>=m||y<0)    return false;
    if(maze[x][y]=='#'||inq[x][y]==true)    return false;

    return true;
}

int BFS()
{
    queue<node>q;
    q.push(S);
    while(!q.empty())
    {
        node top=q.front();
        q.pop();
        if(top.x==T.x&&top.y==T.y)
        {
            return top.step;
        }
        for(int i=0;i<4;i++)
        {
            int newX=top.x+X[i];
            int newY=top.y+Y[i];
            if(test(newX,newY))
            {
                Node.x=newX;Node.y=newY;
                Node.step=top.step+1;
                q.push(Node);
                inq[newX][newY]=true;
            }
        }
    }
    return -1;
}

int main()
{
    scanf("%d%d",&n,&m);
    for(int i=0;i<n;i++)
    {

        for(int j=0;j<m;j++)
        {
            cin>>maze[i][j];
        }
    }
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<m;j++)
        {
            if(maze[i][j]=='S')
            {
                S.x=i;
                S.y=j;
            }
            if(maze[i][j]=='T')
            {
                T.x=i;
                T.y=j;
            }
        }
    }

    S.step=0;
    printf("%d\n",BFS());
    return 0;
}

 

posted @ 2018-05-08 22:42  Somnus、M  阅读(457)  评论(0编辑  收藏  举报