Created
July 16, 2023 02:47
-
-
Save donal56/68916718244516e85ed0c781223420e1 to your computer and use it in GitHub Desktop.
Number of islands - Test code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return 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. | |
* | |
* Example 1: | |
* | |
* Input: grid = [ | |
* ["1","1","1","1","0"], | |
* ["1","1","0","1","0"], | |
* ["1","1","0","0","0"], | |
* ["0","0","0","0","0"] | |
* ] | |
* Output: 1 | |
* Example 2: | |
* | |
* Input: grid = [ | |
* ["1","1","0","0","0"], | |
* ["1","1","0","0","0"], | |
* ["0","0","1","0","0"], | |
* ["0","0","0","1","1"] | |
* ] | |
* Output: 3 | |
*/ | |
class Solution { | |
public int numIslands(char[][] grid) { | |
int m = grid.length; | |
int n = grid[0].length; | |
int islandsNumber = 0; | |
for(int i = 0; i < m; i++) { | |
for(int j = 0; j < n; j++) { | |
if(grid[i][j] == '1') { | |
processCell(i, j, grid, m, n); | |
islandsNumber++; | |
} | |
} | |
} | |
return islandsNumber; | |
} | |
public void processCell(int x, int y, char[][] grid, int m, int n) { | |
if(grid[x][y] == '0') { | |
return; | |
} | |
grid[x][y] = '0'; | |
// check left | |
if(y > 0) { | |
processCell(x, y - 1, grid, m, n); | |
} | |
// check up | |
if(x > 0) { | |
processCell(x - 1, y, grid, m, n); | |
} | |
// check right | |
if(y < n - 1) { | |
processCell(x, y + 1, grid, m, n); | |
} | |
// check down | |
if(x < m - 1) { | |
processCell(x + 1, y, grid, m, n); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment