Cavity Map : HackerRank Problem Solution

You are given a square map of size n x n. Each cell of the map has a value denoting its depth. We will call a cell of the map a cavity if and only if this cell is not on the border of the map and each cell adjacent to it has strictly smaller depth. Two cells are adjacent if they have a common side (edge). You need to find all the cavities on the map and depict them with the uppercase character X.

Input:

4

1112
1912
1892
1234

Output:


1112

1X12
18X2
1234

Implementation:


#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#define MAX 1000

int main() {

    int n,i,j;
    char *a[MAX];
    scanf("%d",&n);
    for(i=0;i<n;i++)
        *(a+i)=(char*)malloc(sizeof(char)*n);
    for(i=0;i<n;i++)
        scanf("%s",*(a+i));
    for(i=0;i<n;i++)
        {
        for(j=0;j<n;j++)
            {
            if(i==0 || i==n-1 || j==0 || j==n-1)
                {
                printf("%c",*(*(a+i)+j));
            }
                else if(((*(*(a+i)+j) > a[i][j-1] && *(*(a+i)+j) > a[i][j+1])) && (a[i][j] > a[i-1][j] && a[i][j] > a[i+1][j]))
                {
                    printf("X");
                }     
            else
                printf("%c",*(*(a+i)+j));
        }
        printf("\n");
    }
    return 0;
}