中级农民
- 积分
- 155
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2014-4-17
- 最后登录
- 1970-1-1
|
根据aiwojiujiu的思路写了下代码
- public class MinimumDaysToReachDestination {
- class Cell {
- public int x, y, h;
- Cell() {
- }
- Cell(int xx, int yy, int hh) {
- x = xx;
- y = yy;
- h = hh;
- }
- }
- class CellComparator implements Comparator<Cell> {
- public int compare(Cell x, Cell y) {
- if (x.h > y.h) {
- return 1;
- } else if (x.h == y.h) {
- return 0;
- } else {
- return -1;
- }
- }
- }
- int[] dx = { 1, -1, 0, 0 };
- int[] dy = { 0, 0, 1, -1 };
- public int getMinimumDaysToReachDestination(int[][] heights) {
- // write your code here
- if (heights == null || heights.length == 0 || heights[0].length == 0) {
- return 0;
- }
- PriorityQueue<Cell> q = new PriorityQueue<Cell>(11,
- new CellComparator());
- int n = heights.length;
- int m = heights[0].length;
- boolean[][] visited = new boolean[n][m];
- q.offer(new Cell(0, 0, heights[0][0]));
- visited[0][0] = true;
- int ans = Integer.MIN_VALUE;
- while (!q.isEmpty()) {
- Cell now = q.poll();
- ans = Math.max(ans, heights[now.x][now.y]);
- if (now.x == n - 1 && now.y == m - 1) {
- return ans;
- }
- for (int i = 0; i < 4; i++) {
- int nx = now.x + dx[i];
- int ny = now.y + dy[i];
- if (0 <= nx && nx < n && 0 <= ny && ny < m && !visited[nx][ny]) {
- visited[nx][ny] = true;
- q.offer(new Cell(nx, ny, Math.max(now.h, heights[nx][ny])));
- }
- }
- }
- return ans == Integer.MIN_VALUE? Integer.MAX_VALUE : ans;
- }
-
-
- public static void main(String[] args) {
- int[][] matrix = {{1, 2},
- {3, 4}};
- int[][] matrix2 = {{1, 3, 5},
- {6, 10, 9},
- {4, 3, 2}};
- MinimumDaysToReachDestination m = new MinimumDaysToReachDestination();
- System.out.println(m.getMinimumDaysToReachDestination(matrix));
- System.out.println(m.getMinimumDaysToReachDestination(matrix2));
- }
- }
复制代码 |
|