Poj3083//dfs to the left wall (right wall) to walk the path of long +bfs to find the shortest way//time:0ms memory:716k#include<iostream> #include <cstring># Include<cstdio> #include <queue>using namespace std; #define MAX 45#define inrange (X->= 0 && X < n && y >=0 && y < m) struct point{int x, y, D; Point (int xx,int yy,int dd): X (xx), Y (yy), D (DD) {}};int n,m;int sx,sy;char mize[max][max];bool vis[max][max];int mov[4][2 ] = {{0,1},{1,0},{0,-1},{-1,0}}; n/a int dfs (int x, int y, int f, int c) {if (mize[x][y] = = ' E ') return 1; int px = x + mov[(f+c)%4][0], py = y + mov[(f+c)%4][1]; Left (right) int fx = x + mov[f][0], fy = y + mov[f][1]; Front side if (mize[px][py] = = '. ' | | mize[px][py] = = ' E ') {f = (f+c)%4; Turn left (turn right) FX = x + mov[f][0], fy = y + mov[f][1]; } while (mize[fx][fy] = = ' # ') {f = (f+4-c)%4; Turn right (turn left) FX = x + mov[f][0], fy = y + mov[f][1]; } return 1 + DFS (FX,FY,F,C);} int BFS (int x, int y) {memset (Vis,false, SizEOF (VIS)); Queue<point> Q; Q.push (Point (x,y,1)); Vis[x][y] = true; while (!q.empty ()) {Point cur = q.front (); Q.pop (); for (int i =0; i < 4;i++) {int tx = cur.x + mov[i][0]; int ty = cur.y + mov[i][1]; if (InRange (tx,ty) && mize[tx][ty]! = ' # ' &&!vis[tx][ty]) {if (mize[tx][ty] = = ' E ') return cur.d+1; Q.push (Point (Tx,ty, cur.d+1)); Vis[tx][ty] = true; }}} return 0;} int main () {//freopen ("In.txt", "R", stdin); int T; scanf ("%d", &t); while (t--) {memset (Vis, false, sizeof (VIS)); scanf ("%d%d", &m,&n); for (int i = 0; i < n;i++) {scanf ("%s", Mize[i]); for (int j = 0; J < m; j + +) if (mize[i][j] = = ' S ') sx = i, sy = j; } int f = 0; for (; f < 4; f++) {int FX = SX + mov[f][0], fy = sy +MOV[F][1]; if (InRange (fx,fy) && mize[fx][fy] = = '. ' | | mize[fx][fy] = = ' E ') break; } printf ("%d%d%d\n", DFS (SX, SY, F, 3), DFS (SX, SY, F, 1), BFS (Sx,sy)); } return 0;}
ACM/ICPC by the Wall-dfs+bfs (POJ3083)