import java.io.*;
import java.util.*;
public class Solution {
static void work() throws IOException{//dijkstra
N = nextInt();
M = nextInt();
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= M; j++) {
board[i][j].init(nextInt());
}
}
pq.add(new int[]{1, 1, 0});
board[1][1].cost = 0;
while (!pq.isEmpty()) {
int[] cur = pq.poll();
Node fr = board[cur[0]][cur[1]];
for (int i = 1; i <= 4; i++) {
if (cur[2] > fr.cost) continue;//dijkstra算法pq效率优化,本题中可以不需要
//offset 下标1、2、3、4与题目中方向相同,
int nx = fr.x + offset[i][0];
if (nx < 1 || nx > N) continue;//判断是否越界
int ny = fr.y + offset[i][1];
if (ny < 1 || ny > M) continue;//判断是否越界
Node to = board[nx][ny];
int c = Math.abs(fr.dirc - i);//i为当前移动方向,使用abs计算移动的成本
if (to.cost > fr.cost + c) {
to.cost = fr.cost + c;
pq.add(new int[]{nx, ny, to.cost});
}
}
}
}
public static void main(String[] args) throws IOException {
for (int i = 1; i <= 500; i++) {//初始化全部数据结构
for (int j = 1; j <= 500; j++) {
board[i][j] = new Node(i, j);
}
}
in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
int T = nextInt();
for (int tc = 1; tc <= T; tc++) {
work();
System.out.println("#" + tc + " " + board[N][M].cost);
}
}
static int nextInt() throws IOException {
in.nextToken();
return (int) in.nval;
}
static final int INF = Integer.MAX_VALUE >> 1;
//进行移动时辅助数组,下标1、2、3、4与题目中方向相同
static final int[][] offset = {{0, 0}, {-1, 0}, {0, 1}, {1, 0}, {0, -1}};
static final Node[][] board = new Node[503][503];
static final PriorityQueue<int[]> pq = new PriorityQueue<>(Comparator.comparingInt(o -> o[2]));
static StreamTokenizer in;
static int N, M;
static class Node {
int x, y, dirc, cost;
Node(int a, int b) {
x = a;
y = b;
}
void init(int d) {
dirc = d;
cost = INF;
}
}
}
2021-10-22
最新推荐文章于 2022-07-01 09:20:08 发布