Poj 3083 Children of the Candy Corn
题目连接:http://poj.org/problem?id=1077
题目描述:给出一个迷宫,#表示墙,S表示起点,E表示终点。求从S到E的优先靠左边的墙走、优先靠右边的墙走和S到E的最短路径。
解法:求优先靠左靠右的路径,用dfs,求最短路径用bfs即可。
dfs中可以用nx = x+move[(i+4)%4][0];ny = y+move[(i+4)%4][1];处理很巧妙
View Code
1 #include<iostream>
2 #include<cstring>
3 #include<cmath>
4 #include<cstdio>
5 #include<queue>
6 #define see(x) cout<<#x<<":"<<x<<endl;
7 using namespace std;
8 const int inf = 9999999;
9 const int N = 50;
10 char map[N][N];
11 typedef struct{
12 int x, y, dis;
13 }Node;
14
15 const int move[4][4] ={{0,-1},{-1,0},{0,1},{1,0}};
16 bool vis[N][N] = {0};
17 int r, c;
18 queue<Node> q;
19 int bfs(){
20 int i;
21 Node temp, temp1;
22 int minn = inf;
23 while(!q.empty()){
24 temp = q.front();
25 q.pop();
26 if(map[temp.x][temp.y]=='E'){
27 if(temp.dis<minn){
28 minn = temp.dis;
29 }
30 }
31
32 else{
33 for(i=0;i<4;i++){
34 temp1.x = temp.x+move[i][0];
35 temp1.y = temp.y+move[i][1];
36 temp1.dis = temp.dis+1;
37 if(temp1.x>=0&&temp1.x<r&&temp1.y>=0&&temp1.y<c&&map[temp1.x][temp1.y]!='#'&&!vis[temp1.x][temp1.y]){
38 vis[temp1.x][temp1.y] = 1;
39 q.push(temp1);
40 }
41 }
42 }
43 }
44 return minn;
45 }
46 int dfs(int x, int y, int dir, char mark){
47 int i, ndir, nx, ny;
48 if(map[x][y]=='E'){
49 return 1;
50 }
51 if(mark=='l'){
52 for(i=dir-1;i<dir+3;i++){
53 nx = x+move[(i+4)%4][0];
54 ny = y+move[(i+4)%4][1];
55 ndir = (i+4)%4;
56 if(nx>=0&&nx<r&&ny>=0&&ny<c&&map[nx][ny]!='#'){
57 // cout<<"nx: "<<nx<<" ny: "<<ny<<" "; see(ndir)
58 return dfs(nx,ny,ndir,mark)+1;
59 }
60 }
61 }
62 if(mark=='r'){
63 for(i=dir+1;i>dir-3;i--){
64 nx = x+move[(i+4)%4][0];
65 ny = y+move[(i+4)%4][1];
66 ndir = (i+4)%4;
67 if(nx>=0&&nx<r&&ny>=0&&ny<c&&map[nx][ny]!='#'){
68 return dfs(nx,ny,ndir,mark)+1;
69 }
70 }
71 }
72 return 0;
73 }
74 int main(){
75 int t, lp, rp, sp;
76 int i, j, k, dir;
77 Node s;
78 scanf("%d",&t);
79 while(t--){
80 scanf("%d%d",&c,&r);
81 for(i=0;i<r;i++)
82 scanf("%s",map[i]);
83 for(i=0;i<r;i++){
84 for(j=0;j<c;j++){
85 if(map[i][j]=='S'){
86 s.x=i; s.y=j; s.dis=1;
87 break;
88 }
89 }
90 }
91 if(s.x==0){
92 dir=3;
93 }
94 else if(s.x==1){
95 dir=1;
96 }
97 else if(s.y==0){
98 dir = 2;
99 }
100 else{
101 dir = 0;
102 }
103 lp = dfs(s.x,s.y,dir,'l');
104
105 vis[s.x][s.y] = 1;
106 rp = dfs(s.x,s.y,dir,'r');
107
108 memset(vis,0,sizeof(vis));
109 vis[s.x][s.y] = 1; s.dis = 1;
110 q.push(s);
111 sp = bfs();
112 printf("%d %d %d\n",lp,rp,sp);
113 }
114 return 0;
115 }