Skip to content

Commit d2aa86e

Browse files
committed
"Number of Islands"
1 parent 5a7e710 commit d2aa86e

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

Diff for: README.md

+3
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ them with C++ Language.
1111

1212
| | Problem | Solution |
1313
| --- | ------------------------------------------------------------ | ------------------ |
14+
| 200 | [Number of Islands] | [C](src/200.c) |
1415
| 199 | [Binary Tree Right Side View] | [C](src/199.c) |
1516
| 198 | [House Robber] | [C](src/198.c) |
1617
| 191 | [Number of 1 Bits] | [C](src/191.c) |
@@ -198,6 +199,8 @@ them with C++ Language.
198199

199200
[LeetCode algorithm problems]: https://leetcode.com/problemset/algorithms/
200201

202+
203+
[Number of Islands]: https://leetcode.com/problems/number-of-islands/
201204
[Binary Tree Right Side View]: https://leetcode.com/problems/binary-tree-right-side-view/
202205
[House Robber]: https://leetcode.com/problems/house-robber/
203206
[Number of 1 Bits]: https://leetcode.com/problems/number-of-1-bits/

Diff for: src/200.c

+54
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
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

Comments
 (0)