UVA - 10047(BFS 标记数组的应用)

22 篇文章 0 订阅
17 篇文章 0 订阅

UVA - 10047

题目

给一个迷宫,从 S 走到 T,每一次操作可以选择改变朝向,或者往当前朝向的方向前进一格,不过到达 T 的时候,底色还是原来的底色 ,(一共有5个底色,走一格变化一次,初始朝向为北),求最小操作。

分析

BFS套模板,不过要注意标记数组的应用,不仅仅是位置的标记,这个题要标记4个状态,位置,朝向,底色。

先到的不一定是最小的,所以要求所有路径最小。

ans = min(ans, cnt.t)

标记数组跟这个题很像
https://blog.csdn.net/GodJing007/article/details/96327387

代码

#include <bits/stdc++.h>
using namespace std;
const int INF = 0x3f3f3f3f;
const int N = 1e2 + 10;

int n, m, ans, cas = 1;
char a[N][N];
int vis[N][N][5][5];
int dir[][2] = {{-1, 0}, {0, -1}, {1, 0}, {0, 1}};

struct node{
    int x, y, d, c, t;      // 位置,朝向,底面颜色
    node(int x, int y, int d, int c, int t):x(x), y(y), d(d), c(c), t(t){}
};

int f(int x, int y){
    if (x >= 1 && x <= n && y <= m && y >= 1)
        return true;
    return false;
}

void bfs(int x, int y){
    queue<node> q;
    memset(vis, 0, sizeof(vis));
    q.push(node(x, y, 0, 0, 0));        // 初始面向北方
    vis[x][y][0][0] = 1;
    while(!q.empty()){
        node cnt = q.front();
        q.pop();
        if(a[cnt.x][cnt.y] == 'T' && cnt.c == 0){
            ans = min(ans, cnt.t);
        }
        for(int i = 1; i <= 3; i += 2){      // 两次转向
            if(!vis[cnt.x][cnt.y][(cnt.d + i) % 4][cnt.c]){
                vis[cnt.x][cnt.y][(cnt.d + i) % 4][cnt.c] = 1;
                q.push(node(cnt.x, cnt.y, (cnt.d + i) % 4, cnt.c, cnt.t + 1));
            }
        }
        int tx = cnt.x + dir[cnt.d][0];
        int ty = cnt.y + dir[cnt.d][1];
        int tc = (cnt.c + 1) % 5;
        if(f(tx, ty) && !vis[tx][ty][cnt.d][tc] && a[tx][ty] != '#'){
            vis[tx][ty][cnt.d][tc] = 1;
            q.push(node(tx, ty, cnt.d, tc, cnt.t + 1));
        }
    }
}

int main()
{
    while(~scanf("%d%d", &n, &m)){
        if(n == 0 && m == 0)
            break;
        int x, y;
        for(int i = 1; i <= n; i++){
            scanf("%s", a[i] + 1);
            for(int j = 1; j <= m; j++){
                if(a[i][j] == 'S'){
                    x = i, y = j;
                }
            }
        }
        ans = INF;
        bfs(x, y);
        if(cas > 1) puts("");
        printf("Case #%d\n", cas++);
        if(ans != INF)
            printf("minimum time = %d sec\n", ans);
        else
            printf("destination not reachable\n");
    }
}
/*
1 6
S.....T

1 3
S#T
10 10
#S.......#
#..#.##.##
#.##.##.##
.#....##.#
##.##..#.#
#..#.##...
#......##.
..##.##...
#.###...#.
#.....###T
0 0
*/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值