2021-10-22

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;
        }
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值