小九来到某地坐缆车,他的钱只能坐一次缆车,所以他想尽量延长坐缆车的时间。已知缆车站分布可以看作是一个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;
}
}