You are presented with an image of a surface photographed by a satellite. The image is a raster image where water is indicated by the letter '.' and the earth is marked ' * '. Adjacent group ' * forms an island. (Two " * " are adjacent if they are horizontal, vertical or diagonal neighbors). Your task is to print the number of islands in the bitmap.
Input Example: -
.........** **......*** ........... ...*....... *........*. *.........*
Output: - 5
Here is my implementation that takes the space O(r * c) and O(r * c) , where r is not. rows and c is the total number of col columns.
#include <stdio.h> #define COLS 12 void markVisted(char map[][COLS], int visited[][COLS], int row, int col, int rowCount) { if((row < 0) || (row >= rowCount) || (col < 0) || (col >= COLS) || (map[row][col] != '*') || (visited[row][col] == 1)) return; visited[row][col] = 1; //calling neighbours markVisted(map, visited, row+1, col, rowCount); markVisted(map, visited, row, col+1, rowCount); markVisted(map, visited, row-1, col, rowCount); markVisted(map, visited, row, col-1, rowCount); markVisted(map, visited, row+1, col+1, rowCount); markVisted(map, visited, row-1, col-1, rowCount); markVisted(map, visited, row-1, col+1, rowCount); markVisted(map, visited, row+1, col-1, rowCount); } int countIslands(char map[][COLS], int visited[][COLS], int rowCount) { int i, j, count = 0; for(i=0; i<rowCount; ++i){ for(j=0; j<COLS; ++j){ if((map[i][j] == '*') && (visited[i][j] == 0)){ ++count; markVisted(map, visited, i, j, rowCount); } } } return count; } int main() { char map[][COLS] = { "*..........", "**........*", "...........", "...*.......", "*........*.", "..........*" }; int rows = sizeof(map)/sizeof(map[0]); int visited[rows][COLS], i, j; for(i=0; i<rows; ++i){ for(j=0; j<COLS; ++j) visited[i][j] = 0; } printf("No. of islands = %d\n", countIslands(map, visited, rows)); return 0; }
please suggest the best logic for this problem
suggestions for improving my solution are also welcome.