View Code of Problem 2597

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;//'.'  , '#' ,,'S','E';
int dir [4][2]={{1,0},{-1,0},{0,1},{0,-1}};
int n,m;
int mins=9999999;
char mp[105][105];
int vis[105][105];
bool check (int x ,int y )
{
    if ((x<n&&x>=0)&&(y<m&&y>=0))
        return true;
    return false;
}
int dfs (int x,int y,int dp)
{
    if (mp[x][y]=='E')
    {
        mins=min(mins,dp);
        return 1;
    }
    for (int i=0;i<4;i++)
    {
        int tmpx=dir[i][0]+x;
        int tmpy=dir[i][1]+y;
        if (mp[tmpx][tmpy]=='#')
            continue;
        if (check (tmpx,tmpy)==true&&vis[tmpx][tmpy]==0)
        {
            vis[tmpx][tmpy]=1;
            dfs (tmpx,tmpy,dp+1);
            vis[tmpx][tmpy]=0;
        }

    }
    return 0;
}
int main()
{

    int stx,sty;
    while (scanf ("%d%d",&n,&m)!=EOF){
        mins=9999999;
        for (int i=0;i<n;i++){
            scanf ("%s",mp[i]);
            for (int j=0;j<m;j++){
                if (mp[i][j]=='S')
                {
                    stx=i;
                    sty=j;
                }
            }
        }
        memset (vis,0,sizeof (vis));
        vis[stx][sty]=1;
        dfs (stx,sty,0);
        printf ("%d\n",mins==9999999?0:mins);

    }

}

Double click to view unformatted code.


Back to problem 2597