【三次过】Lintcode 1386. 坐缆车

小九来到某地坐缆车,他的钱只能坐一次缆车,所以他想尽量延长坐缆车的时间。已知缆车站分布可以看作是一个n x m的矩阵,每个格点代表缆车站的高度。他可以从任一站点开始坐缆车,缆车只能从矮的高度移动到高的高度,花费1单位的时间。缆车可以朝着八个方向移动。(上下左右、左上、左下、右上、右下)问小九最多能坐多久缆车?

样例

样例1

输入: mat = 
[
    [1,2,3],
    [4,5,6],
    [7,8,9]
]
输出: 7
解释:
1->2->3->5->7->8->9 这条路线是最长的。

样例2

输入: mat = 
[
    [1,2,3],
    [6,5,4],
    [7,8,9]
]
输出: 9
解释:
1->2->3->4->5->6->7->8->9这条路线是最长的。

注意事项

  • 1 <= n, m <= 20
  • 输入的缆车站高度不超过100000

解题思路:

对于每个点作为起点进行八个方向的dfs即可

public class Solution {
    /**
     * @param height: the Cable car station height
     * @return: the longest time that he can ride
     */
    public int cableCarRide(int[][] height) {
        // Write your code here
        int ans = 0;
        int n = height.length;
        int m = height[0].length;
        
        for(int i = 0; i < n; i++) {
            for(int j = 0; j < m; j++) {
                int temp = dfs(i, j, n, m, height);
                ans = Math.max(ans, temp);
            }
        }
        return ans;
    }
    
    int[] dx = {-1, -1, -1, 0, 0, 1, 1, 1};
    int[] dy = {-1, 0, 1, -1, 1, -1, 0, 1};
    
    int dfs(int x, int y, int n, int m, int[][] height) {
        int res = 0;
        for(int i = 0; i < 8; i++) {
            int tx = x + dx[i];
            int ty = y + dy[i];
            if(tx < 0 || tx >= n || ty < 0 || ty >= m || height[tx][ty] <= height[x][y])
                continue;
            res = Math.max(res, dfs(tx, ty, n, m, height));
        }
        return res + 1;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值