POJ1573 Robot Motion(dfs)

Robot Motion

题目链接:

http://poj.org/problem?id=1573

解题思路:

简单模拟即可。

AC代码:

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

int dx[] = {0,-1,0,1},dy[] = {-1,0,1,0};
char maze[11][11];
int vis[11][11];
int m,n,ans;

void dfs(int x,int y){
    //cout<<x<<y<<endl;
    if(x<0 || x>=m || y<0 || y>=n){
        printf("%d step(s) to exit\n",ans);
        return ;
    }
    if(vis[x][y]){
        printf("%d step(s) before a loop of %d step(s)\n",vis[x][y]-1,ans-vis[x][y]+1);
        return ;
    }
    ans++;
    if(maze[x][y] == 'W'){
        vis[x][y] = ans;
        dfs(x+dx[0],y+dy[0]);
    }
    else if(maze[x][y] == 'N'){
        vis[x][y] = ans;
        dfs(x+dx[1],y+dy[1]);
    }
    else if(maze[x][y] == 'E'){
        vis[x][y] = ans;
        dfs(x+dx[2],y+dy[2]);
    }
    else{
        vis[x][y] = ans;
        dfs(x+dx[3],y+dy[3]);
    }
}

int main(){
    int x;
    while(scanf("%d%d%d",&m,&n,&x),m+n+x){
        for(int i = 0; i < m; i++)
            scanf("%s",maze[i]);
        ans = 0;
        memset(vis,0,sizeof(vis));
        dfs(0,x-1);
    }
    return 0;
}



你可能感兴趣的:(DFS)