LeetCode 417. Pacific Atlantic Water Flow _ Problems with Pacific Atlantic Water Flow

Topic description

Given a  m x n matrix of non-negative integers representing the heights of individual cells on a continent. The "Pacific" is on the left and upper boundaries of the continent, while the "Atlantic" is on the right and lower boundaries of the continent.

It is stipulated that the water flow can only flow in four directions: up, down, left and right, and can only flow from high to low or at the same height.

Find the coordinates of those land units where currents can flow into both the "Pacific" and the "Atlantic".

hint:

  1. The order of output coordinates does not matter
  2. Both m  and  n  are less than 150

Example:

Given the following 5x5 matrix:

  Pacific Ocean ~ ~ ~ ~ ~
       ~  1   2   2   3  (5) *
       ~  3   2   3  (4) (4) *
       ~  2   4  (5)  3   1  *
       ~ (6) (7)  1   4   5  *
       ~ (5)  1   1   2   4  *
          * * * * * Atlantic

return:

[[0, 4], [1, 3], [1, 4], [2, 2], [3, 0], [3, 1], [4, 0]] (parenthesized unit).

Carry out a deep search from the Pacific coast and the Atlantic coast respectively, mark the two-dimensional array flag of the respective flags if the conditions are met, and finally traverse the two two-dimensional arrays. If the same position has not been marked, it means that this position can reach the Pacific Ocean and Atlantic.

        public List<int[]> pacificAtlantic(int[][] matrix) {
		List<int[]> list = new ArrayList<int[]>();

		if (matrix.length <= 0 || matrix[0].length <= 0)
			return list;
		int rows = matrix.length;
		int cols = matrix[0].length;
		byte[][] flag1 = new byte[rows][cols];
		byte[][] flag2 = new byte[rows][cols];
		for (int i = 0; i < cols; i++) {
			dfs(matrix, flag1, 0, i);
			dfs(matrix, flag2, rows - 1, i);
		}
		for (int i = 0; i < rows; i++) {
			dfs(matrix, flag1, i, 0);
			dfs(matrix, flag2, i, cols - 1);
		}

		for (int i = 0; i < rows; i++) {
			for (int j = 0; j < cols; j++) {
				if (flag1[i][j] == 1 && flag2[i][j] == 1)
					list.add(new int[] { i, j });
			}
		}
		return list;
	}

	private void dfs(int[][] matrix, byte[][] flag, int x, int y) {
		int rows = matrix.length;
		int cols = matrix[0].length;
		flag[x][y] = 1;
		// 上
		if (x - 1 >= 0 && matrix[x - 1][y] >= matrix[x][y] && flag[x - 1][y] != 1)
			dfs(matrix, flag, x - 1, y);
		// 下
		if (x + 1 < rows && matrix[x + 1][y] >= matrix[x][y] && flag[x + 1][y] != 1)
			dfs(matrix, flag, x + 1, y);
		// 左
		if (y - 1 >= 0 && matrix[x][y - 1] >= matrix[x][y] && flag[x][y - 1] != 1)
			dfs(matrix, flag, x, y - 1);
		// 右
		if (y + 1 < cols && matrix[x][y + 1] >= matrix[x][y] && flag[x][y + 1] != 1)
			dfs(matrix, flag, x, y + 1);

	}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325966106&siteId=291194637