int calculateIsland(int size, int arr[size][size]){
int i, j;
int count = 0;
int visited[size][size];
for(i=0; i<size; i++){
for(j=0; j<size; j++){
visited[i][j] = 0;
}
}
for(i=0; i<size; i++){
for(j=0; j<size; j++){
if(arr[i][j] == 1 && visited[i][j] == 0){
visited[i][j] = 1;
checkVertically(size, arr, visited, i, j);
checkHorizontally(size, arr, visited, i, j);
checkDiagonally(size, arr, visited, i, j);
count++;
}
}
}
printf("Total no of island: %d", count);
}
void checkVertically(int size, int arr[size][size], int visited[size][size], int x, int y){
if(arr[x+1][y] == 1 && visited[x+1][y] == 0 && x+1 < size){
visited[x+1][y] = 1;
checkDiagonally(size, arr, visited, x+1, y);
checkVertically(size, arr, visited, x+1, y);
checkHorizontally(size, arr, visited, x+1, y);
}
if(arr[x-1][y] == 1 && visited[x-1][y] == 0 && x-1 > -1){
visited[x-1][y] = 1;
checkDiagonally(size, arr, visited, x-1, y);
checkVertically(size, arr, visited, x-1, y);
checkHorizontally(size, arr, visited, x-1, y);
}
}
void checkHorizontally(int size, int arr[size][size], int visited[size][size], int x, int y){
if(arr[x][y+1] == 1 && visited[x][y+1] == 0 && y+1 < size){
visited[x][y+1] = 1;
checkVertically(size, arr, visited, x, y+1);
checkDiagonally(size, arr, visited, x, y+1);
checkHorizontally(size, arr, visited, x, y+1);
}
if(arr[x][y-1] == 1 && visited[x][y-1] == 0 && y-1 > -1){
visited[x][y-1] = 1;
checkVertically(size, arr, visited, x, y-1);
checkDiagonally(size, arr, visited, x, y-1);
checkHorizontally(size, arr, visited, x, y-1);
}
}
void checkDiagonally(int size, int arr[size][size], int visited[size][size], int x, int y){
if(arr[x+1][y+1] == 1 && visited[x+1][y+1] == 0 && x+1 < size && y+1 < size){
visited[x+1][y+1] = 1;
checkVertically(size, arr, visited, x+1, y+1);
checkDiagonally(size, arr, visited, x+1, y+1);
checkHorizontally(size, arr, visited, x+1, y+1);
}
if(arr[x-1][y-1] == 1 && visited[x-1][y-1] == 0 && x-1 > -1 && y-1 > -1){
visited[x-1][y-1] = 1;
checkVertically(size, arr, visited, x-1, y-1);
checkDiagonally(size, arr, visited, x-1, y-1);
checkHorizontally(size, arr, visited, x-1, y-1);
}
if(arr[x+1][y-1] == 1 && visited[x+1][y-1] == 0 && x+1 < size && y-1 > -1){
visited[x+1][y-1] = 1;
checkVertically(size, arr, visited, x+1, y-1);
checkDiagonally(size, arr, visited, x+1, y-1);
checkHorizontally(size, arr, visited, x+1, y-1);
}
if(arr[x-1][y+1] == 1 && visited[x-1][y+1] == 0 && x-1 > -1 && y+1 < size){
visited[x-1][y+1] = 1;
checkVertically(size, arr, visited, x-1, y+1);
checkDiagonally(size, arr, visited, x-1, y+1);
checkHorizontally(size, arr, visited, x-1, y+1);
}
}
void main(){
int i, j;
int size;
printf("Enter size of array: ");
scanf("%d", &size);
int arr[size][size];
for(i=0; i<size; i++){
for(j=0; j<size; j++){
printf("Enter element [%d][%d]: ", i, j);
scanf("%d", &arr[i][j]);
}
}
calculateIsland(size, arr);
}
0 Comments