poj3083 dfs + bfs

7 篇文章 0 订阅

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

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

#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;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值