Short DFS Java solution


  • 7
    S

    Hi guys!

    The approach is same as in other posts, I just tried to make the code compact and clean.

    Have a nice coding!


    public class Solution {
        private static final int[][] DIRS = new int[][]{{1,0},{-1,0},{0,1},{0,-1}};
        private static final char L = '1', W = '0';
        
        public void dfsFill(char[][] g, int x, int y) {
            if (x >= 0 && x < g.length && y >= 0 && y < g[0].length && g[x][y] == L) {
                g[x][y] = W;
                for (int[] d : DIRS) dfsFill(g, x + d[0], y + d[1]);
            }
        }
        
        public int numIslands(char[][] grid) {
            int num = 0;
            for (int i = 0; i < grid.length; i++) {
                for (int j = 0; j < grid[0].length; j++) {
                    if (grid[i][j] == L) {
                        num++;
                        dfsFill(grid, i, j);
                    }
                }
            }
            return num;
        }
    }

  • 0
    A

    I like your approaching with recursive DFS. Maybe faster than my BFS, as I'd have to use an additional Queue


  • 0
    B

    I like your coding style!!


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.