import java.util.ArrayDeque;
import java.util.Scanner;
/**
* BFS
* 关键:三位数组标记走过的点,3滴血和5滴血走过的点是不一样的
*/
public class P2802 {
static int T, n, m, ans;
static int[][] map;
static boolean[][][] flag;
static int[][] dir = { { -1, 0 }, { +1, 0 }, { 0, -1 }, { 0, +1 } };
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m = sc.nextInt();
map = new int[n][m];
flag = new boolean[n][m][7];
NodeB start = null, end = null;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
map[i][j] = sc.nextInt();
if (map[i][j] == 2) {
start = new NodeB(i, j, 0, 6);
}
if (map[i][j] == 3) {
end = new NodeB(i, j, 0, 0);
}
}
}
bfs(start, end);
System.out.println(ans);
}
private static void bfs(NodeB start, NodeB end) {
ArrayDeque<NodeB> que = new ArrayDeque<NodeB>();
que.add(start);
flag[start.x][start.y][start.p] = true;
while (!que.isEmpty()) {
NodeB node = que.getFirst();
que.removeFirst();
for (int i = 0; i < 4; i++) {
NodeB dirNode = new NodeB(node.x + dir[i][0], node.y + dir[i][1], node.time + 1, node.p - 1);
if (isVal(dirNode)) {
if (map[dirNode.x][dirNode.y] == 4) {
dirNode.p = 6;
}
if (dirNode.equals(end) && dirNode.p > 0) {
ans = dirNode.time;
return;
}
que.addLast(dirNode);
flag[dirNode.x][dirNode.y][dirNode.p] = true;
}
}
}
ans = -1;
return;
}
private static boolean isVal(NodeB dirNode) {
int x = dirNode.x;
int y = dirNode.y;
int p = dirNode.p;
return x >= 0 && x < n && y >= 0 && y < m && map[x][y] != 0 && flag[x][y][p] == false && p > 0;
}
}
class NodeB {
int x, y, time, p;
public NodeB(int x, int y, int time, int p) {
super();
this.x = x;
this.y = y;
this.time = time;
this.p = p;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + x;
result = prime * result + y;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
NodeB other = (NodeB) obj;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
}
}
P2802 回家(BFS)
猜你喜欢
转载自blog.csdn.net/qq_28635317/article/details/112837936
今日推荐
周排行