今天和大家聊的问题叫做 太平洋大西洋水流问题,我们先来看题面:https://leetcode-cn.com/problems/pacific-atlantic-water-flow/
There is an m x n rectangular island that borders both the Pacific Ocean and Atlantic Ocean. The Pacific Ocean touches the island's left and top edges, and the Atlantic Ocean touches the island's right and bottom edges.
The island is partitioned into a grid of square cells. You are given an m x n integer matrix heights where heights[r][c] represents the height above sea level of the cell at coordinate (r, c).
The island receives a lot of rain, and the rain water can flow to neighboring cells directly north, south, east, and west if the neighboring cell's height is less than or equal to the current cell's height. Water can flow from any cell adjacent to an ocean into the ocean.
Return a 2D list of grid coordinates result where result[i] = [ri, ci] denotes that rain water can flow from cell (ri, ci) to both the Pacific and Atlantic oceans.
给定一个 m x n 的非负整数矩阵来表示一片大陆上各个单元格的高度。“太平洋”处于大陆的左边界和上边界,而“大西洋”处于大陆的右边界和下边界。规定水流只能按照上、下、左、右四个方向流动,且只能从高到低或者在同等高度上流动。请找出那些水流既可以流动到“太平洋”,又能流动到“大西洋”的陆地单元的坐标。
示例
解题
可以用DFS和BFS,这里用DFS
首先,我们要找的既能流进太平洋,又能流进大西洋的,所以,我们分开讨论,找可以流进太平洋的坐标,再找大西洋的坐标.
其次,我们不需要一个一个坐标判断,我们只要考虑边界就行,我拿上边界为例,上边界都可以流入太平洋,所以我们可以从上边界进行深度遍历,就是找比它水位高的坐标,都可以流到它这里.
最后,我们把这上下左右四个边界都考虑一下
class Solution { public List<List<Integer>> pacificAtlantic(int[][] matrix) { List<List<Integer>> result = new ArrayList<>(); int m = matrix.length; if (m == 0) return result; int n = matrix[0].length; // 定义 table1、table2 存储是否流入太平洋 boolean[][] table1 = new boolean[m][n]; boolean[][] table2 = new boolean[m][n]; // 能否触达上、下 for (int i = 0; i < n; i++) { dfs(matrix, 0, i, matrix[0][i], table1); dfs(matrix, m - 1, i, matrix[m - 1][i], table2); } // 能否触达左右 for (int i = 0; i < m; i++) { dfs(matrix, i, 0, matrix[i][0], table1); dfs(matrix, i, n - 1, matrix[i][n - 1], table2); } // 取出都能触达的点 for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (table1[i][j] && table2[i][j]) { List<Integer> list = new ArrayList<>(); list.add(i); list.add(j); result.add(list); } } } return result; } public void dfs(int[][] matrix, int x, int y, int pre, boolean[][] table) { if (x < 0 || x >= matrix.length || y < 0 || y >= matrix[0].length || matrix[x][y] < pre || // 当前值小于上一个值 table[x][y] // 当前值已经被标记 ) return; table[x][y] = true; // 上下左右 dfs(matrix, x - 1, y, matrix[x][y], table); dfs(matrix, x + 1, y, matrix[x][y], table); dfs(matrix, x, y - 1, matrix[x][y], table); dfs(matrix, x, y + 1, matrix[x][y], table); } }
好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。