HDU-1035 Robot Motion
题意:给出一图,求跳出此图的步骤,若遇到环则不同输出。
思路:dfs.
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1035
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <cstdio> 2 #include <cstring> 3 #include <cstdlib> 4 #include <cmath> 5 #include <string> 6 #include <algorithm> 7 #include <iostream> 8 using namespace std; 9 const int N=11; 10 11 int n,m,s; 12 char map[N][N]; 13 bool flag[N][N]; 14 int step[N][N]; 15 16 void dfs(int x,int y,int cnt){ 17 if(x==0||y==0||x>n||y>m){printf("%d step(s) to exit\n",cnt);return ;} 18 if(flag[x][y]){ 19 printf("%d step(s) before a loop of %d step(s)\n",step[x][y],cnt-step[x][y]); 20 return ; 21 } 22 step[x][y]=cnt; 23 flag[x][y]=true; 24 if(map[x][y]=='N') dfs(x-1,y,cnt+1); 25 else if(map[x][y]=='S') dfs(x+1,y,cnt+1); 26 else if(map[x][y]=='E') dfs(x,y+1,cnt+1); 27 else dfs(x,y-1,cnt+1); 28 } 29 30 int main(){ 31 32 // freopen("data.in","r",stdin); 33 // freopen("data.out","w",stdout); 34 35 while(scanf("%d%d",&n,&m),n||m){ 36 scanf("%d",&s); 37 getchar(); 38 for(int i=1;i<=n;i++){ 39 for(int j=1;j<=m;j++) 40 scanf("%c",&map[i][j]); 41 getchar(); 42 } 43 memset(step,0,sizeof(step)); 44 memset(flag,false,sizeof(flag)); 45 dfs(1,s,0); 46 } 47 return 0; 48 }