题目:http://acm.hdu.edu.cn/showproblem.php?pid=2612
题目大意说一下,有一个地图上面有两个人,要去KFC见面,然后需要求出二者到KFC的最短距离之和,这原本是一个简简单单的bfs搜索,但是两个人的出现,让它加了点难度
思路:第一次搜索从Y开始,然后求出他到达每个KFC的距离,然后打个表出来,存着备用,然后从M开始搜索,在求出他到达每个KFC的距离,将这两次的结果加起来找出其中最短的
坑:这里有个问题,让我wa了一上午,连中午的泡面都不香了,原本按照上面的思路,是顶呱呱的,但是有一组实例会有问题
5 5
Y..#@
...M#
.....
.....
@....
如果按照上面的思路,这里就会是0,因为存在一家KFC不能到达!
所以我们需要在筛选的时候判断一下,去除最后结果中为0的部分,然后再去寻找最短的那个即可
import java.util.LinkedList;
import java.util.Scanner;
public class Main {
private static String[] map;
private static int[][] visited;
private static int m;
private static int n;
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
while(sc.hasNext()) {
m = sc.nextInt();
n = sc.nextInt();
map = new String[m];
for(int i = 0; i < m; i++) {
map[i] = sc.next();
}
visited = new int[m][n];
int num = 0;
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
visited[i][j] = 0;
if(map[i].charAt(j)=='@') {
num++;
}
}
}
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
if(map[i].charAt(j)=='Y') {
bfs(i, j, 0);
}
}
}
int[] kfc = new int[num];
int index = 0;
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
if(map[i].charAt(j)=='@') {
kfc[index] = visited[i][j];
index++;
}
visited[i][j] = 0;
}
}
index = 0;
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
if(map[i].charAt(j)=='M') {
bfs(i, j, 0);
}
}
}
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
if(map[i].charAt(j)=='@') {
kfc[index] = visited[i][j] + kfc[index];
index++;
}
visited[i][j] = 0;
}
}
int min = 10000005;
for(int i = 0; i < kfc.length; i++) {
//去除为零的部分,寻找最短的
if(kfc[i]!=0&&kfc[i]<min) {
min = kfc[i];
}
}
long result = min * 11;
System.out.println(result);
}
}
public static void bfs(int x, int y, int step) {
//定义移动需要用到的数组
int[] dx = {1, -1, 0, 0};
int[] dy = {0, 0, 1, -1};
//用集合冒充队列应该没人发现吧
LinkedList<node> queue = new LinkedList<node>();
node no = new node(x, y, 0);
visited[x][y] = 1;
queue.addLast(no);
while(queue.size()!=0) {
node now = queue.removeFirst();
if(map[now.getX()].charAt(now.getY())=='@') {
visited[now.getX()][now.getY()] = now.getStep();
}
for(int i = 0; i < 4; i++) {
int xx = now.getX() + dx[i];
int yy = now.getY() + dy[i];
//下一个节点在合法范围内且没有访问过
if((xx>=0)&&(xx<m)&&(yy>=0)&&(yy<n)&&(visited[xx][yy]==0)) {
if(map[xx].charAt(yy)=='.'||map[xx].charAt(yy)!='#') {
queue.addLast(new node(xx, yy, now.getStep()+1));
visited[xx][yy]=1;
}
}
}
}
}
}
class node{
private int x;
private int y;
private int step;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getStep() {
return step;
}
public void setStep(int step) {
this.step = step;
}
public node(int x, int y, int step) {
super();
this.x = x;
this.y = y;
this.step = step;
}
}