417 pacific atlantic water flow

https://leetcode.com/problems/pacific-atlantic-water-flow/

class Solution {
    int[][] DIR = new int[][]{{-1, 0}, {1, 0}, {0, 1}, {0, -1}};
    // int[][] ADIR = new int[][]{{0, -1}, {-1, 0}};
    private class Node {
        int i;
        int j;
        public Node(int i, int j) {
            this.i = i;
            this.j = j;
        }
        public String toString() {
            return this.i + " " + this.j;
        }
    }
    public List<List<Integer>> pacificAtlantic(int[][] heights) {
        int m = heights.length;
        int n = heights[0].length;
        int[][] pflood = new int[m][n];
        Queue<Node> queue = new ArrayDeque<>();
        Set<String> visited = new HashSet<>();
        for (int i = 0; i < m; i++) {
            queue.offer(new Node(i, 0));
        }
        for (int j = 0; j < n; j++) {
            queue.offer(new Node(0, j));
        }
        while (!queue.isEmpty()) {
            Node node = queue.poll();
            if (visited.contains(node.toString())) continue;
            visited.add(node.toString());
            
            pflood[node.i][node.j] = 1;
            
            for (int[] dir : DIR) {
                int x = dir[0] + node.i;
                int y = dir[1] + node.j;
                if (x >= 0 && x < m && y >= 0 && y < n) {
                    if (heights[node.i][node.j] <= heights[x][y]) {
                        queue.offer(new Node(x, y));
                    }
                }
            }
        }
        visited.clear();
        for (int i = 0; i < m; i++) {
            queue.offer(new Node(i, n - 1));
        }
        for (int j = 0; j < n; j++) {
            queue.offer(new Node(m - 1, j));
        }
        List<List<Integer>> ans = new ArrayList<>();
        while (!queue.isEmpty()) {
            Node node = queue.poll();
            if (visited.contains(node.toString())) continue;
            visited.add(node.toString());
            if (pflood[node.i][node.j] == 1) {
                ans.add(Arrays.asList(node.i, node.j));
            }
            for (int[] dir : DIR) {
                int x = dir[0] + node.i;
                int y = dir[1] + node.j;
                if (x >= 0 && x < m && y >= 0 && y < n) {
                    if (heights[node.i][node.j] <= heights[x][y]) {
                        queue.offer(new Node(x, y));
                    }
                }
            }
        }
        return ans;
    }
}
  1. ไปŽๆตทๆด‹ๅๅ‘ๆทนๅคง้™†

  2. ๅ››ไธชๆ–นๅ‘้ƒฝ่ฆๅฐ่ฏ•

  3. queueไธ€ๅผ€ๅง‹ๅฏไปฅ่พน็•ŒไธŠ็š„node้ƒฝๆ”พ่ฟ›ๅŽป

่ฟ™้“้ข˜ๅ’Œ542ไธ€ๆ ท้ƒฝๆ˜ฏไธ€ๅผ€ๅง‹ๅŠ ไธ€ๅ †node่ฟ›ๅŽป็š„็ฑปๅž‹

Last updated