Counts "islands" of 1s in sea of 0s (2d array matrix) This solution surpassed 100% of submissions for efficiency! My method was to recursively check surrounding values and change any contiguous "land" to "water". Is there a better way to write what I wrote?


  Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.


class Solution {
public int numIslands(char[][] grid) {
    int islands = 0;

    for (int i = 0; i &lt; grid.length; i++) {
        for (int j = 0; j &lt; grid[i].length; j++) {
            if (grid[i][j] == '1') {
                islands++;
                destroyIsland(grid, i, j);
            }
        }
    }

    return islands;
}

public void destroyIsland(char[][] grid, int i, int j) {
    grid[i][j] = '0';
    if (i &lt; grid.length - 1 &amp;&amp; grid[i+1][j] == '1') {
        destroyIsland(grid, i+1, j);
    }
    if (i &gt; 0 &amp;&amp; grid[i-1][j] == '1') {
        destroyIsland(grid, i-1, j);
    }
    if (j &lt; grid[i].length - 1 &amp;&amp; grid[i][j+1] == '1') {
        destroyIsland(grid, i, j+1);
    }
    if (j &gt; 0 &amp;&amp; grid[i][j-1] == '1') {
        destroyIsland(grid, i, j-1);
    }
}
}
The code seems correct. The only missing part is


  You may assume all four edges of the grid are all surrounded by water.


which means that numIslands may iterate

    for (int i = 1; i &lt; grid.length - 1; i++) {
        for (int j = 1; j &lt; grid[i].length - 1; j++) {


and do not bother destroyIsland with validating the surroundings.