Find the number of islands in a given matrix and area of every island

Dear,

I am counting the number of islands in a given matrix and try to find the area of every island.
http://en.wikipedia.org/wiki/Connect…raph_theory%29

Now finally remove the errors and my result is
1 islands area is 1
2 islands area is 1
3 islands area is 1
4 islands area is 1
5 islands area is 1
Number of islands is: 5

But I need a result according to my matrix is

1 islands area is 4
2 islands area is 3
3 islands area is 1
4 islands area is 1
5 islands area is 1
Number of islands is: 5

1-I am thinking that there is some problem for calling the area.

what do you think?

Please reply me


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99

#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include<conio.h>
#define ROW 5
#define COL 5
int markIsland(int arr[][COL], int i, int j, int m, int n,int area);
int countIslands(int arr[][COL], int m, int n);

int markIsland(int arr[][COL], int i, int j, int m, int n,int area)
{

// area=1;
{
arr[i][j] = -1;

if(i-1 >= 0)
{

if(j-1 >= 0 && arr[i-1][j-1] == 1)
markIsland(arr, i-1, j-1, m, n,area);

if(arr[i-1][j] == 1)
markIsland(arr, i-1, j, m, n,area);

if(j+1 < n && arr[i-1][j+1] == 1)
markIsland(arr, i-1, j+1, m, n,area);

}

if(i+1 < m)
{

if(j-1 >= 0 && arr[i+1][j-1] == 1)
markIsland(arr, i+1, j-1, m, n,area);

if(arr[i+1][j] == 1)
markIsland(arr, i+1, j, m, n,area);

if(j+1 < n && arr[i+1][j+1] == 1)
markIsland(arr, i+1, j+1, m, n,area);

}

if(j-1 >= 0 && arr[i][j-1] == 1)
markIsland(arr, i, j-1, m, n,area);

if(j+1 < n && arr[i][j+1] == 1)
markIsland(arr, i, j+1, m, n,area);

area++;

}
return area;
}

int countIslands(int arr[][COL], int m, int n)
{
int count = 0;

for(int i=0; i&lt;m; i++)
{
for(int j=0; j&lt;n; j++)

if(arr[i][j] == -1)
arr[i][j] = 1;

count++;

}

return count;
}

main()

{
int area=1,count=1;
int v, i,j;
int m = ROW;
int n = COL;
int arr[][COL]= { {1, 1, 0, 0, 0},
{0, 1, 0, 0, 1},
{1, 0, 0, 1, 1},
{0, 0, 0, 0, 0},
{1, 0, 1, 0, 1}
};
for(v=0;v&lt; countIslands(arr,m,n);v++)
{
printf(&quot; %d islands area is %d\n&quot;, count++,area);
// printf(&quot; %d islands area is %d\n&quot;, countIslands(arr,m,n),markIsland(arr,i,j,m,n,area) );
}
printf(&quot;Number of islands is: %d\n&quot;, countIslands(arr,m,n));

getch();
}

Topic archived. No new replies allowed.