poj3083 dfs + bfs

给定迷宫,深搜求向左搜索和向右搜索走出迷宫需要的步数,广搜求走出迷宫最少的步数。

注意方向数组,还有横纵坐标。

#include <iostream>
#include <cstdio>
#include <queue>
#include <cstring>
using namespace std;

int w, h, dist[45][45];
char maze[45][45];
struct point { int x, y; } s;
int dir[4][2] = {{0, 1}, {-1, 0}, {0, -1}, {1, 0}};

int bfs()
{
    memset (dist, 0, sizeof (dist));
    queue <point> q;
    q.push(s);
    dist[s.y][s.x] = 1;
    while (!q.empty()) {
        point cur = q.front();
        q.pop();
        for (int i = 0; i <= 3; i++) {
            point nxt;
            nxt.x = cur.x + dir[i][0];
            nxt.y = cur.y + dir[i][1];
            if (!dist[nxt.y][nxt.x] && nxt.x >= 0 && nxt.x < w && nxt.y >= 0 && nxt.y < h && maze[nxt.y][nxt.x] != '#') {
                dist[nxt.y][nxt.x] = dist[cur.y][cur.x] + 1;
                if (maze[nxt.y][nxt.x] == 'E') return dist[nxt.y][nxt.x];
                q.push(nxt);
            }
        }
    }
}

int dfs(int x, int y, int toward, char ch)
{
    if (maze[y][x] == 'E') return 1;

    int tx, ty, i, to; 
    if (ch == 'l') {
       for (i = toward - 1; i <= toward + 2; i++) { //注意该怎样循环
           to = (i + 4) % 4;         //to表示的是下次搜索时的方向,上右下左对应的to指分别为0 1 2 3;
                                             //同时 to 又表示本次搜索的方向数组的下标,要达到这两个目的则需要循环方式和方向数组的配合          
           tx = x + dir[to][0]; ty = y + dir[to][1];
           if (tx >= 0 && tx < w && ty >= 0 && ty < h && maze[ty][tx] != '#')
              return 1 + dfs (tx, ty, to, ch);
       }
    }
    else if (ch == 'r') {
       for (i = toward + 1; i >=  toward - 2; i--) {
           to = (i + 4) % 4;
           tx = x + dir[to][0]; ty = y + dir[to][1];
           if (tx >= 0 && tx < w && ty >= 0 && ty < h && maze[ty][tx] != '#')
              return 1 + dfs (tx, ty, to, ch);
       }
    }
}
int main()
{
    int n, i, j;
    bool mark;

    scanf ("%d", &n);
    while (n--) {
        scanf ("%d%d", &w, &h);
        getchar();
        mark = false;
        for (i = 0; i < h; i++) {
            gets(maze[i]);
            for (j = 0; j < w && !mark; j++)
                if (maze[i][j] == 'S') {
                   s.x = j; s.y = i; mark = true;
                }
        }
        int toward;
        if (s.y == 0) toward = 0;
        else if (s.x == w - 1) toward = 1;
        else if (s.y == h - 1) toward = 2;
        else toward = 3;
        printf ("%d %d %d\n", dfs(s.x, s.y, toward, 'l'), dfs(s.x, s.y, toward, 'r'), bfs());
    }
    return 0;
}



你可能感兴趣的:(struct)