Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 7fa2b54

Browse files
Number of island
Signed-off-by: Leo Ma <begeekmyfriend@gmail.com>
1 parent 33a7380 commit 7fa2b54

File tree

3 files changed

+68
-1
lines changed

3 files changed

+68
-1
lines changed

002_add_two_numbers/add_two_numbers.c

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,8 @@ struct ListNode {
88
struct ListNode *next;
99
};
1010

11-
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
11+
static struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2)
12+
{
1213
int carry_num = 0;
1314
int first = 1;
1415
struct ListNode *res = NULL;
@@ -90,6 +91,11 @@ static void show(struct ListNode *ln)
9091

9192
int main(int argc, char **argv)
9293
{
94+
if (argc < 3) {
95+
fprintf(stderr, "Usage: ./test n1 n2\n");
96+
exit(-1);
97+
}
98+
9399
struct ListNode *l1 = node_build(argv[1]);
94100
struct ListNode *l2 = node_build(argv[2]);
95101
struct ListNode *res = addTwoNumbers(l1, l2);

200_number_of_islands/Makefile

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
all:
2+
gcc -O2 -o test islands.c

200_number_of_islands/islands.c

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
#include <string.h>
4+
5+
static void recursive(char** grid, int row_size, int col_size, int row, int col)
6+
{
7+
grid[row][col] = '0';
8+
9+
if (row > 0 && grid[row - 1][col] == '1') {
10+
recursive(grid, row_size, col_size, row - 1, col);
11+
}
12+
13+
if (row < row_size - 1 && grid[row + 1][col] == '1') {
14+
recursive(grid, row_size, col_size, row + 1, col);
15+
}
16+
17+
if (col > 0 && grid[row][col - 1] == '1') {
18+
recursive(grid, row_size, col_size, row, col - 1);
19+
}
20+
21+
if (col < col_size - 1 && grid[row][col + 1] == '1') {
22+
recursive(grid, row_size, col_size, row, col + 1);
23+
}
24+
}
25+
26+
static int numIslands(char** grid, int gridRowSize, int gridColSize)
27+
{
28+
int i, j, count = 0;
29+
for (i = 0; i < gridRowSize; i++) {
30+
for (j = 0; j < gridColSize; j++) {
31+
if (grid[i][j] == '1') {
32+
recursive(grid, gridRowSize, gridColSize, i, j);
33+
count++;
34+
}
35+
}
36+
}
37+
38+
return count;
39+
}
40+
41+
int main(int argc, char **argv)
42+
{
43+
if (argc < 2) {
44+
fprintf(stderr, "Usage: ./test 11000 11000 00100 00011\n");
45+
exit(-1);
46+
}
47+
48+
int i, j;
49+
int row_size = argc - 1;
50+
int col_size = strlen(argv[1]);
51+
char **grid = malloc(row_size * sizeof(char *));
52+
for (i = 0; i < row_size; i++) {
53+
grid[i] = malloc(col_size);
54+
memcpy(grid[i], argv[i + 1], col_size);
55+
}
56+
57+
printf("%d\n", numIslands(grid, row_size, col_size));
58+
return 0;
59+
}

0 commit comments

Comments
 (0)