简单的最短路径,采用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;
}