阅读理解题。。。。。。
题目很简单,让你顺时针方向DFS一次求路径长,逆时针方向DFS一次求路径长,在BFS一下求最短路径。
#include <iostream> #include <cstdio> #include <cstring> #include <cmath> #include <queue> using namespace std; int w,h,map[50][50]; struct coordinate { int x; int y; }; coordinate s,e; bool judge(coordinate a) { if (a.x < 0 || a.x >= h || a.y < 0 || a.y >= w) return false; if (map[a.x][a.y] == 8) return false; return true; } int dir_right[4][2]={{0,-1},{1,0},{0,1},{-1,0}},dr; int dir_left[4][2]={{0,1},{1,0},{0,-1},{-1,0}},dl; int DFS_Right(coordinate t,int cnt) { if (t.x == e.x && t.y == e.y) return cnt; coordinate tc; int i,j; dr+=3; dr%=4; for (i=0; i<4; i++) { tc.x=t.x+dir_right[dr][0]; tc.y=t.y+dir_right[dr][1]; if (judge(tc)) { j=DFS_Right(tc,cnt+1); if (j != 0) return j; } dr++; dr%=4; } } int DFS_Left(coordinate t,int cnt) { if (t.x == e.x && t.y == e.y) return cnt; coordinate tc; int i,j; dl+=3; dl%=4; for (i=0; i<4; i++) { tc.x=t.x+dir_left[dl][0]; tc.y=t.y+dir_left[dl][1]; if (judge(tc)) { j=DFS_Left(tc,cnt+1); if (j != 0) return j; } dl++; dl%=4; } } int v[50][50]; void BFS() { coordinate tc,ttc; int i; queue<coordinate> q; while (!q.empty()) q.pop(); q.push(s); v[s.x][s.y]=1; while (!q.empty()) { tc=q.front(); q.pop(); for (i=0; i<4; i++) { ttc.x=tc.x+dir_left[i][0]; ttc.y=tc.y+dir_left[i][1]; if (judge(ttc)) { if (v[tc.x][tc.y]+1 < v[ttc.x][ttc.y]) { v[ttc.x][ttc.y]=v[tc.x][tc.y]+1; q.push(ttc); } } } } } int main() { int i,j,prob,scoor; char tc; scanf("%d",&prob); while (prob--) { scanf("%d%d",&w,&h); getchar(); for (i=0; i<h; i++) { for (j=0; j<w; j++) { scanf("%c",&tc); if (tc == '#') map[i][j]=8; else if (tc == '.') map[i][j]=0; else if (tc == 'S') { map[i][j]=1; s.x=i; s.y=j; } else { map[i][j]=-1; e.x=i; e.y=j; } } getchar(); } dl=0; dr=0; memset(v,0x3f,sizeof(v)); BFS(); printf("%d %d %d\n",DFS_Left(s,0)+1,DFS_Right(s,0)+1,v[e.x][e.y]); } }