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<m; i++)
{
for(int j=0; j<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< countIslands(arr,m,n);v++)
{
printf(" %d islands area is %d\n", count++,area);
// printf(" %d islands area is %d\n", countIslands(arr,m,n),markIsland(arr,i,j,m,n,area) );
}
printf("Number of islands is: %d\n", countIslands(arr,m,n));
getch();
}
|