import java.math.BigInteger;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
import java.util.Stack;
public class Main
{
public static int move[][]= {{0,1},{0,-1},{1,0},{-1,0}};
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
while (sc.hasNext())
{
int a ,b;a=sc.nextInt();b=sc.nextInt();
char arr[][]=new char[a][b];
int ymap[][]=new int[a][b];
int mmap[][]=new int[a][b];
int yx,yy,mx,my;yx=0;yy=0;mx=0;my=0;
for (int i = 0; i < arr.length; i++)
{
arr[i]=sc.next().toCharArray();
for (int j = 0; j <b; j++)
{
if (arr[i][j]=='Y')
{
yx=i;yy=j;
}
if (arr[i][j]=='M')
{
mx=i;my=j;
}
}
}
/
Queue<node> bfs1=new LinkedList<node>();
bfs1.add(new node(yx, yy,0));
while(!bfs1.isEmpty()) {
node now=bfs1.poll();
for (int i = 0; i < move.length; i++)
{
int x=now.a+move[i][0];int y=now.b+move[i][1];
if (x>=0 &&x<a && y>=0 && y<b && ymap[x][y]==0 && arr[x][y]!='#')
{
ymap[x][y]=now.step+1;
bfs1.add(new node(x, y, now.step+1));
}
}
}
Queue<node>bfs2=new LinkedList<node>();
bfs2.add(new node( mx,my,0));
while(!bfs2.isEmpty()) {
node now=bfs2.poll();
for (int i = 0; i < move.length; i++)
{
int x=now.a+move[i][0];int y=now.b+move[i][1];
if (x>=0 &&x<a && y>=0 && y<b &&mmap[x][y]==0 && arr[x][y]!='#')
{
mmap[x][y]=now.step+1;
bfs2.add(new node(x, y, now.step+1));
}
}
}
long min=Integer.MAX_VALUE;
for (int i = 0; i <a; i++)
{
for (int j = 0; j < b; j++)
{
if (ymap[i][j]!=0 && mmap[i][j]!=0)
{
ymap[i][j]+=mmap[i][j];
if (arr[i][j]=='@')
{
min=Math.min(min, ymap[i][j]*11);
}
}
}
}
System.out.println(min);
}
}
}
class node{
int a ,b,step;
public node(int a,int b,int c) {
this.a=a;this.b=b;step=c;
}
}
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交