输入是一个 N*N的矩阵,代表地势高度。如果下雨水流只能流去比他矮或者一样高的地势。
矩阵左边和上边是太平洋,右边和下边是大西洋。求出所有的能同时流到两个大洋的点。For example:
|
|
括号里即为结果:
[[0, 4], [1, 3], [1, 4], [2, 2], [3, 0], [3, 1], [4, 0]]
import java.util.*; class Solution { public List<List<Integer>> waterflow(int[][] map) { int nrow = map.length; int ncolumn = map[0].length; List<List<Integer>> result = new ArrayList<>(); boolean[][] pacificRecord = new boolean[map.length][map[0].length]; boolean[][] atlanticRecord = new boolean [map.length][map[0].length]; for(int i = 0; i < nrow; i++){ DFS(map, i, 0, pacificRecord); } for (int i = 0; i < ncolumn; i++){ DFS(map, 0, i, pacificRecord); } for(int i = 0; i < nrow; i++){ DFS(map, i, ncolumn - 1, atlanticRecord); } for (int i = 0; i < ncolumn; i++){ DFS(map, nrow - 1, i, atlanticRecord); } for (int i = 0; i < nrow; i++){ for(int j = 0; j < ncolumn; j++){ if(pacificRecord[i][j] && atlanticRecord[i][j]){ List<Integer> pair = new ArrayList<>(); pair.add(i); pair.add(j); result.add(pair); } } } return result; } private void DFS(int[][] map, int row, int column, boolean[][] record) { if (record[row][column]) { return; } int nrow = map.length; int ncolumn = map[0].length; int cur = map[row][column]; record[row][column] = true; int leftColumn = column - 1; int rightColumn = column + 1; int upperRow = row - 1; int loweRow = row + 1; if (leftColumn >= 0 && map[row][leftColumn] >= cur) DFS(map, row, leftColumn, record); if (rightColumn < ncolumn && map[row][rightColumn] >= cur) DFS(map, row, rightColumn, record); if (upperRow >= 0 && map[upperRow][column] >= cur) DFS(map, upperRow, column, record); if (loweRow < nrow && map[loweRow][column] >= cur) DFS(map, loweRow, column, record); } } class Main{ public static void main(String[] args){ int[][] map = new int[][] {{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,}}; Solution sol = new Solution(); List<List<Integer>> result = sol.waterflow(map); for(List<Integer> pair: result){ System.out.println(pair.get(0) + " " + pair.get(1)); } return; } }