Skip to content

Instantly share code, notes, and snippets.

@oguzaktas
oguzaktas / number_of_islands.java
Created July 24, 2024 16:04
Given an mxn 2D binary grid which represents a map of 1s (land) and 0s (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.
class Solution {
public int numIslands(char[][] grid) {
int count = 0; // initialize the count to 0
if (grid.length == 0) { // if the grid is empty, return 0
return 0;
}
// iterate through each cell in the grid
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
// if a land cell (1) is found, increment the count