Easy to Read Java DFS Flood From Ocean
Top answer right now uses 2 matrices to track visited but we can do it with one - use codes for visited by Pacific, Atlantic, or both.\n\n\nclass Solution {\n  
Top answer right now uses 2 matrices to track visited but we can do it with one - use codes for visited by Pacific, Atlantic, or both.\n\n```\nclass Solution {\n    public List<List<Integer>> pacificAtlantic(int[][] matrix) {\n        List<List<Integer>> res = new ArrayList();\n        if (matrix.length == 0 || matrix[0].length == 0)  return res;\n        // visited by pacific == -1, atlantic == -2, both == -3\n        int[][] visited = new int[matrix.length][matrix[0].length];\n        for (int i = 0; i < matrix.length; i++) {\n            dfs(matrix, visited, i, 0, -1);\n            dfs(matrix, visited, i, matrix[0].length-1, -2);\n        }\n        for (int i = 0; i < matrix[0].length; i++) {\n            dfs(matrix, visited, 0, i, -1);\n            dfs(matrix, visited, matrix.length-1, i, -2);\n        }\n        \n        \n        for (int y = 0; y < matrix.length; y++) {\n            for (int x = 0; x < matrix[0].length; x++) {\n                if (visited[y][x] == -3) {\n                    res.add(Arrays.asList(y,x));\n                }\n            }\n        }\n        return res;\n    }\n    \n    private void dfs(int[][] matrix, int[][] visited, int y, int x, int code) {\n        int val = matrix[y][x];\n        int vis = visited[y][x];\n        if (vis == code || vis == -3) return;\n        visited[y][x] = vis < 0 ? -3 : code;\n        \n        boolean left = x > 0 && matrix[y][x-1] >= val;\n        boolean right = x < matrix[0].length -1 && matrix[y][x+1] >= val;\n        boolean up = y > 0 && matrix[y-1][x] >= val;\n        boolean down = y < matrix.length - 1 && matrix[y+1][x] >= val;\n        \n        if (left) dfs(matrix, visited, y, x-1, code);\n        if (right) dfs(matrix, visited, y, x+1, code);\n        if (up) dfs(matrix, visited, y-1, x, code);\n        if (down) dfs(matrix, visited, y+1, x, code);\n    }\n}\n```
[]