#include <stdio.h>
#include <stdbool.h>
#define ROWS 4
#define COLS 5
// Directions for neighbors (up, down, left, right)
int directions[4][2] = {{-1,0},{1,0},{0,-1},{0,1}};
void dfs(int grid[ROWS][COLS], bool visited[ROWS][COLS], int r, int c) {
if (r < 0 || r >= ROWS || c < 0 || c >= COLS) return; // boundary check
if (visited[r][c]) return; // already visited
if (grid[r][c] == 0) return; // water cell
visited[r][c] = true; // mark current land as visited
for (int i = 0; i < 4; i++) {
int nr = r + directions[i][0];
int nc = c + directions[i][1];
dfs(grid, visited, nr, nc); // explore neighbors
}
}
int numIslands(int grid[ROWS][COLS]) {
bool visited[ROWS][COLS] = {{false}};
int count = 0;
for (int r = 0; r < ROWS; r++) {
for (int c = 0; c < COLS; c++) {
if (grid[r][c] == 1 && !visited[r][c]) {
dfs(grid, visited, r, c); // mark all connected land
count++;
}
}
}
return count;
}
int main() {
int grid[ROWS][COLS] = {
{1,1,0,0,0},
{1,1,0,0,0},
{0,0,1,0,0},
{0,0,0,1,1}
};
int islands = numIslands(grid);
printf("Number of islands = %d\n", islands);
return 0;
}
if (r < 0 || r >= ROWS || c < 0 || c >= COLS) return;
stop if out of grid bounds
if (visited[r][c]) return;
skip if cell already visited
if (grid[r][c] == 0) return;
skip water cells
mark current land cell visited
for (int i = 0; i < 4; i++) { dfs(grid, visited, r + directions[i][0], c + directions[i][1]); }
explore all four neighbors recursively
if (grid[r][c] == 1 && !visited[r][c]) { dfs(grid, visited, r, c); count++; }
start DFS for new island and increment count