aiaiask.com©

开花即结果 提问即答案

计算中庸行者在m*n地形高度矩阵中最大连续移动次数(Java实现)
原始问题:

计算中庸行者在m*n地形高度矩阵中最大连续移动次数(Java实现)

import java.util.LinkedList;
import java.util.Queue;

public class Solution {
    public int maxMoves(int[][] heightMap) {
        int m = heightMap.length;
        int n = heightMap[0].length;
        boolean[][] visited = new boolean[m][n];
        Queue<int[]> queue = new LinkedList<>();
        int[][] directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
        int[][] result = new int[m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                result[i][j] = Integer.MAX_VALUE;
            }
        }
        queue.offer(new int[]{0, 0});
        result[0][0] = 0;
        while (!queue.isEmpty()) {
            int[] cur = queue.poll();
            int x = cur[0];
            int y = cur[1];
            if (visited[x][y]) {
                continue;
            }
            visited[x][y] = true;
            for (int[] direction : directions) {
                int newX = x + direction[0];
                int newY = y + direction[1];
                if (newX >= 0 && newX < m && newY >= 0 && newY < n && result[newX][newY] > result[x][y] + Math.abs(heightMap[x][y] - heightMap[newX][newY])) {
                    result[newX][newY] = result[x][y] + Math.abs(heightMap[x][y] - heightMap[newX][newY]);
                    queue.offer(new int[]{newX, newY});
                }
            }
        }
        return result[m - 1][n - 1];
    }
}
计算中庸行者在m*n地形高度矩阵中最大连续移动次数(Java实现)
https://www.aiaiask.com/ask/46145.html
AI / 模型DeepSeek
时间 / DATESeptember 6, 2023, 8:38 PM
语言zh-CN
IP / 区域浙江 杭州