HDU 1035 簡單題
阿新 • • 發佈:2018-11-08
#include <iostream> #include <algorithm> #include <cstdio> #include <string> #include <cstring> #include <cstdlib> #include <Map> #include <cmath> using namespace std; #define ll long long int const int maxn=12; char Map[maxn][maxn]; int dp[maxn][maxn]; int n,m,k; int dir[4][2]={{1,0},{-1,0},{0,1},{0,-1}}; //S N E W bool isout(int i,int j) { if(i<1 || i>n || j<1 || j>m ) return true; else return false; } int main() { while( EOF!=scanf("%d %d",&n,&m) && n && m) { scanf("%d",&k); int i,j; for(i=1;i<=n;i++){ char temp[maxn]; scanf("%s",temp); sprintf(Map[i],"*%s",temp); } memset(dp,0,sizeof(dp)); dp[1][k]=1; int x=1,y=k;//記錄的是當前位置的座標 while(1) { //S N E W int nx,ny; if('S'==Map[x][y]){ nx=x+dir[0][0]; ny=y+dir[0][1]; }else if('N'==Map[x][y]){ nx=x+dir[1][0]; ny=y+dir[1][1]; }else if('E'==Map[x][y]){ nx=x+dir[2][0]; ny=y+dir[2][1]; }else if('W'==Map[x][y]){ nx=x+dir[3][0]; ny=y+dir[3][1]; } if(isout(nx,ny)){//判斷能不能出去 cout << dp[x][y] <<" step(s) to exit" << endl; break; } if(0!=dp[nx][ny]){//已經走過,就會陷入迴圈 cout << dp[nx][ny]-1 << " step(s) before a loop of " << dp[x][y]-dp[nx][ny]+1 << " step(s)" << endl; break; } dp[nx][ny]=dp[x][y]+1; x=nx,y=ny; } } return 0; }