【hihocoder】 1092. Have Lunch Together

简单的最短路径,采用bfs。其中只要找到两个相邻的S,就分别对两个S进行bfs。

这里的要点在于,S当成了#,不能通过。

/**
 *  @author         johnsondu	
 *  @time           Oct 5th, 2015
 *  @status         Accepted 
 *  @type           Shortest path
 *  @url            http://hihocoder.com/problemset/problem/1092
 */
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <string>
#include <queue>
using namespace std;

const int N = 10005;
const int M = 105;
const int INF = 0x7fffff;

struct Node{
	int x, y;
	int step;
};

int n, m, ans, ans1, ans2, tmpAns;
char mat[M][M];
bool mark[M][M];
int dir[4][2] = {-1, 0, 1, 0, 0, -1, 0, 1};

//判断S是否相邻
void judge(int x, int y, bool &flag)
{
	if(x < 0 || y < 0 || x >= n || y >= m) return;
	if(mat[x][y] == 'S') flag = true;
}

//bfs中,判断是否可走
bool safe(int x, int y)
{
	if(x < 0 || y < 0 || x >= n || y >= m) return false;
	if(mark[x][y]) return false;
	if(mat[x][y] == '#' || mat[x][y] == 'S' || mat[x][y] == 'P') return false;
	return true;
}

//普通的bfs
void bfs(int x, int y)
{
    memset(mark, false, sizeof(mark));
	Node cur, pre;
	queue<Node> q;
	cur.x = x;
	cur.y = y;
	cur.step = 0;
	mark[x][y] = true;
	q.push(cur);
	while(!q.empty()) {
		pre = q.front();
		q.pop();
		for(int k = 0; k < 4; k ++) {
			cur.x = pre.x + dir[k][0];
			cur.y = pre.y + dir[k][1];
			cur.step = pre.step + 1;
			if(safe(cur.x, cur.y)) {
				if(mat[cur.x][cur.y] == 'H') {
                    tmpAns = min(cur.step, tmpAns);
					continue;
				}
				mark[cur.x][cur.y] = true;
				q.push(cur);
			}
		}
	}
}

int main()
{
	cin >> n >> m;
	for(int i = 0; i < n; i ++)
		cin >> mat[i];

    ans = INF;
	for(int i = 0; i < n; i ++)
		for(int j = 0; j < m; j ++) {
			if(mat[i][j] == 'S') {
				bool flag = false;
                int tx, ty;
				for(int k = 0; k < 4; k ++)
				{
				    tx = i + dir[k][0];
				    ty = j + dir[k][1];
					judge(tx, ty, flag);
					if(flag) break;
				}
				if(flag) {
                    tmpAns = INF;
					bfs(i, j);
                    ans1 =  tmpAns;
                    tmpAns = INF;
                    bfs(tx, ty);
                    ans2 = tmpAns;
                    ans = min(ans, ans1 + ans2);
				}
			}
		}
	if(ans >= INF) cout << "Hi and Ho will not have lunch." << endl;
	else cout << ans << endl;
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值