Easy to follow Java Solution


  • 0
    A
    public int numIslands(char[][] grid) {
    	if (grid == null || grid.length == 0)
    		return 0;
    	boolean[][] visit = new boolean[grid.length][grid[0].length];
    	int count = 0;
    	for (int i = 0; i < grid.length; i++)
    		for (int j = 0; j < grid[0].length; j++)
    			if (grid[i][j] == '1' && visit[i][j] == false) {
    				count++;
    				tour(grid, visit, i, j);
    			}
    	return count;
    }
    
    public void tour(char[][] grid, boolean[][] visit, int i, int j) {
    	if (i < 0 || i >= grid.length || j < 0 || j >= grid[0].length)
    		return;
    	if (grid[i][j] == '1' && visit[i][j] == false) {
    		visit[i][j] = true;
    		tour(grid, visit, i, j + 1);
    		tour(grid, visit, i, j - 1);
    		tour(grid, visit, i + 1, j);
    		tour(grid, visit, i - 1, j);
    	}
    }

Log in to reply
 

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