Cavity Map Hackerrank problem solution

Cavity Map Hackerrank

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 Format

The first line contains an integer, n, denoting the size of the map. Each of the following n lines contains n positive digits without spaces. Each digit (1-9) denotes the depth of the appropriate area.

Constraints
1<=n<=100 Output Format Output n lines, denoting the resulting map. Each cavity should be replaced with character X. Sample Input 4 1112 1912 1892 1234 Sample Output 1112 1X12 18X2 1234 Explanation The two cells with the depth of 9 fulfill all the conditions of the Cavity definition and have been replaced by X.

Solution

Firstly, copy the whole map into another array. Iterate through each cell of the map, and simply check whether the cell is a cavity or not. If it is, mark the cell as cavity in another array. Finally, output another array.

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

int main(){
int n,i,j;
scanf("%d",&n);
int a[n][n];
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
scanf("%1d",&a[i][j]);
}
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if( (i>=1)&&(i<n-1) && (j>=1)&&(j<n-1) )
{
if( (a[i][j] > a[i-1][j]) && (a[i][j] > a[i][j+1])
&& (a[i][j] > a[i+1][j]) && (a[i][j] > a[i][j-1]) )
printf("X");
else
printf("%d",a[i][j]);
}
else
printf("%d",a[i][j]);
}
printf("\n");
}
return 0;
}
n = input()
data = []
res = [[ for i in range(n)] for i in range(n)]
for i in range(n):
data.append(list(raw_input()))
for i in range(1, n - 1):
for j in range(1, n - 1):
t = data[i][j]
if (t > data[i - 1][j] and t > data[i][j - 1]
and t > data[i + 1][j] and t > data[i][j + 1]):
res[i][j] = 'X'
for i in range(n):
for j in range(n):
if res[i][j] == 'X':
data[i][j] = 'X'
for i in data:
print "".join(i)
#include <bits/stdc++.h>

using namespace std;

int N;
char grid;
char grid2;

int main()
{
scanf("%d\n", &N);
for(int i=0; i<N; i++)
gets(grid[i]);
memcpy(grid2, grid, sizeof grid2);
for(int i=1; i<N-1; i++)
for(int j=1; j<N-1; j++)
if(grid[i][j]>grid[i+1][j])
if(grid[i][j]>grid[i-1][j])
if(grid[i][j]>grid[i][j+1])
if(grid[i][j]>grid[i][j-1])
grid2[i][j]='X';
for(int i=0; i<N; i++)
puts(grid2[i]);
return 0;
}

hasectic

A web developer(Front end and Back end), and DBA at csdamu.com. Currently working as Salesforce Developer @ Tech Matrix IT Consulting Private Limited. Check me @about.me/s.saifi