POJ 1101
#include <iostream> #include <string> #define MAXN 78 #define min _min #define inf 123456789 using namespace std; char _m[MAXN][MAXN]; bool mark[MAXN][MAXN]; int dp[MAXN][MAXN]; int dis[4][2] = {0,1,0,-1,1,0,-1,0}; int dis_mark[4] = {4,3,2,1}; int min; int x_2; int y_2; int real_w; int real_h; void dfs(int x,int y,int dir,int step); int main() { //freopen("acm.acm","r",stdin); // freopen("out.txt","w",stdout); int w; int h; int i; int j; int x_1; int y_1; int temp_x; int temp_y; string s; int time = 0; while(cin>>w>>h,w||h) { cout<<"Board #"<<++ time<<":"<<endl; getchar(); int time_in = 0; real_w = w+2; real_h = h+2; memset(_m,' ',sizeof(_m)); for(i = 1; i <= h; ++ i) { getline(cin,s); for(j = 1; j <= w; ++ j) { _m[i][j] = s[j-1]; } } while(cin>>y_1>>x_1>>y_2>>x_2,x_1||y_1||x_2||y_2) { cout<<"Pair "<<++ time_in<<": "; memset(mark,false,sizeof(mark)); for(i = 0; i < MAXN; ++ i) { for(j = 0; j < MAXN; ++ j) { dp[i][j] = inf; } } min = inf; for(i = 0; i < 4; ++ i) { temp_x = x_1 + dis[i][0]; temp_y = y_1 + dis[i][1]; if((_m[temp_x][temp_y] != 'X' ||_m[temp_x][temp_y] == 'X' && temp_x == x_2 && temp_y == y_2) && !mark[temp_x][temp_y]) { mark[temp_x][temp_y] = true; dfs(temp_x,temp_y,dis_mark[i],1); mark[temp_x][temp_y] = false; } } if(min == inf) { cout<<"impossible."<<endl; } else { cout<<min; cout<<" segments."<<endl; } } cout<<endl; } } //上 1 //下 2 //左 3 //右 4 void dfs(int x,int y,int dir,int step) { if(x == x_2 && y == y_2) { if(step < min) { min = step; } return; } if(step < dp[x][y]) { dp[x][y] = step; } else { return; } int i; int j; int temp_x; int temp_y;// 右 for(i = 0; i < 4; ++ i) { temp_x = dis[i][0] + x; temp_y = dis[i][1] + y; if(temp_x >= 0 && temp_x < real_h && temp_y >= 0 && temp_y <= real_w &&( _m[temp_x][temp_y] != 'X' || _m[temp_x][temp_y] == 'X' && temp_x == x_2 && temp_y == y_2)&& !mark[temp_x][temp_y]) { mark[temp_x][temp_y] = true; if(dis_mark[i] != dir) { dfs(temp_x,temp_y,dis_mark[i],step+1); if(step+1 < dp[temp_x][temp_y]) dp[temp_x][temp_y] = step+1; } else { dfs(temp_x,temp_y,dis_mark[i],step); if(step < dp[temp_x][temp_y]) dp[temp_x][temp_y] = step; } mark[temp_x][temp_y] = false; } } }
关注我的公众号,当然,如果你对Java, Scala, Python等技术经验,以及编程日记,感兴趣的话。
技术网站地址: vmfor.com