|
| 1 | +#include <stdio.h> |
| 2 | +#include <stdbool.h> |
| 3 | +#include <stdlib.h> |
| 4 | +#include <string.h> |
| 5 | + |
| 6 | +void dfs(char **grid, bool **visited, int i, int j, int numRows, int numColumns) { |
| 7 | + if (i >= 0 && i < numRows && j >= 0 && j < numColumns && !visited[i][j]) { |
| 8 | + visited[i][j] = 1; |
| 9 | + if (grid[i][j] == '1') { /* island */ |
| 10 | + dfs(grid, visited, i, j - 1, numRows, numColumns); /* left */ |
| 11 | + dfs(grid, visited, i, j + 1, numRows, numColumns); /* right */ |
| 12 | + dfs(grid, visited, i - 1, j, numRows, numColumns); /* up */ |
| 13 | + dfs(grid, visited, i + 1, j, numRows, numColumns); /* down */ |
| 14 | + } |
| 15 | + } |
| 16 | +} |
| 17 | + |
| 18 | +int numIslands(char **grid, int numRows, int numColumns) { |
| 19 | + if (grid == NULL || numRows == 0 || strlen(grid[0]) == 0) |
| 20 | + return 0; |
| 21 | + |
| 22 | + int i, j; |
| 23 | + int count = 0; |
| 24 | + |
| 25 | + bool **visited = (bool **)calloc(numRows, sizeof(bool *)); |
| 26 | + for (i = 0; i < numRows; i++) { |
| 27 | + visited[i] = (bool *)calloc(numColumns, sizeof(bool)); |
| 28 | + } |
| 29 | + |
| 30 | + for (i = 0; i < numRows; i++) { |
| 31 | + for (j = 0; j < numColumns; j++) { |
| 32 | + if (!visited[i][j]) { /* has not been visited */ |
| 33 | + if (grid[i][j] == '1') /* it's an island */ |
| 34 | + count++; |
| 35 | + dfs(grid, visited, i, j, numRows, numColumns); |
| 36 | + } |
| 37 | + } |
| 38 | + } |
| 39 | + return count; |
| 40 | +} |
| 41 | + |
| 42 | +int main() { |
| 43 | + int row = 3; |
| 44 | + int col = 3; |
| 45 | + char **grid = (char **)calloc(1, sizeof(char *)); |
| 46 | + |
| 47 | + grid[0] = "111"; |
| 48 | + grid[1] = "010"; |
| 49 | + grid[2] = "111"; |
| 50 | + |
| 51 | + /* should be 1 */ |
| 52 | + printf("%d\n", numIslands(grid, row, col)); |
| 53 | + return 0; |
| 54 | +} |
0 commit comments