广搜 基础 走迷宫 记录路径

###############################
Origin:POJ3984
Type:BFS
##############################
#include <iostream>
#include <cstdio>
#include <stack>
#include <queue>
#include <cstring>
#define N 5
using namespace std;
const int dx[4] = {0, 0, -1, 1};
const int dy[4] = {-1, 1, 0, 0};
int fa[N][N], grid[N][N];
bool vis[N][N];

inline bool inbound (int x, int y)
{
    return (0<=x && x<N && 0<=y && y<N);
}

void bfs(int start, int aim)
{
    int x = start / N, y = start % N;
    fa[x][y] = start;
    vis[x][y] = true;
    queue<int>q;
    q.push(start);
    while (!q.empty()){
        int temp = q.front();
        q.pop();
        x = temp / N, y = temp % N;
        int nx, ny;
        for (int i=0; i<4; i++){
            nx = x + dx[i];
            ny = y + dy[i];
            if (inbound(nx, ny) && !grid[nx][ny] && !vis[nx][ny]){
                fa[nx][ny] = temp;
                int a = nx * N + ny;
                if (a == aim) return ;
                q.push(a);
                vis[nx][ny] = 1;
            }
        }
    }
}

void trace(int aim)
{
    int x =aim/N,y =aim%N,fx,fy;
    stack<int> dir;
    dir.push (aim);
    while (1){
        fx = fa[x][y] / N;
        fy = fa[x][y] % N;
        if (fx == x && fy == y) break;
        dir.push(fa[x][y]);
        x = fx, y = fy;
    }
    while (!dir.empty()){

 printf("(%d, %d)\n",dir.top()/N,dir.top()%N);
     dir.pop();
    }
}
int main()
{
  for(int i=0; i<N; i++)
    for(int j=0; j<N; j++)
        scanf("%d",&grid[i][j]);
    memset(vis, 0, sizeof(vis));
    memset(fa, 0, sizeof(fa));
    bfs(0, N*N-1);
    trace(N*N-1);
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值