3
\$\begingroup\$

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 < grid.length; i++) {
 for (int j = 0; j < 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 < grid.length - 1 && grid[i+1][j] == '1') {
 destroyIsland(grid, i+1, j);
 }
 if (i > 0 && grid[i-1][j] == '1') {
 destroyIsland(grid, i-1, j);
 }
 if (j < grid[i].length - 1 && grid[i][j+1] == '1') {
 destroyIsland(grid, i, j+1);
 }
 if (j > 0 && grid[i][j-1] == '1') {
 destroyIsland(grid, i, j-1);
 }
}
}
200_success
146k22 gold badges190 silver badges479 bronze badges
asked Jan 21, 2019 at 23:29
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

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 < grid.length - 1; i++) {
 for (int j = 1; j < grid[i].length - 1; j++) {

and do not bother destroyIsland with validating the surroundings.

answered Jan 22, 2019 at 2:39
\$\endgroup\$
2
  • 1
    \$\begingroup\$ I interpreted that as "all cells outside the bounds should be interpreted as water", which makes the original correct and yours faulty. \$\endgroup\$ Commented Jan 26, 2019 at 9:46
  • \$\begingroup\$ @MarkJeronimus, you are correct. This solution would not pass the test. \$\endgroup\$ Commented Feb 2, 2019 at 3:08

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.