Cavity Map HackerRank Solution in C, C++, Java, Python

You are given a square map as a matrix of integer strings. 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, or edge.

Find all the cavities on the map and replace their depths with the uppercase character X.

Example

grid=[‘989′,’191′,’111’]

The grid is rearranged for clarity:

989
191
111

Return:

989
1X1
111

The center cell was deeper than those on its edges: [8,1,1,1]. The deep cells in the top two corners do not share an edge with the center cell, and none of the border cells is eligible.

Function Description

Complete the cavityMap function in the editor below.

cavityMap has the following parameter(s):

string grid[n]: each string represents a row of the grid
Returns

string{n}: the modified grid
Input Format

The first line contains an integer , the number of rows and columns in the grid.

Each of the following lines (rows) contains positive digits without spaces (columns) that represent the depth at .

Sample Input

STDIN Function
----- --------
4 grid[] size n = 4
1112 grid = ['1112', '1912', '1892', '1234']
1912
1892
1234

Sample Output

1112
1X12
18X2
1234

Explanation

The two cells with the depth of 9 are not on the border and are surrounded on all sides by shallower cells. Their values are replaced by X.

 

Cavity Map HackerRank Solution in C

#include <stdio.h>
#include <string.h>
#include <stdbool.h>

#define clr(ar) memset(ar, 0, sizeof(ar))
#define read() freopen("lol.txt", "r", stdin)

int n;
int dx[] = {0, 0, -1, 1};
int dy[] = {-1, 1, 0, 0};
char str[1010][1010], res[1010][1010];

int main(){
    int i, j, k;

    while (scanf("%d", &n) != EOF){
        for (i = 0; i < n; i++) scanf("%s", str[i]);
        for (i = 0; i < n; i++){
            for (j = 0; j < n; j++){
                res[i][j] = str[i][j];
                if (i == 0 || j == 0 || i == (n - 1) || j == (n - 1)) continue;

                int max = -1;
                for (k = 0; k < 4; k++){
                    int x = i + dx[k];
                    int y = j + dy[k];
                    if (str[x][y] > max) max = str[x][y];
                }
                if (max < str[i][j]) res[i][j] = 'X';
            }
            res[i][n] = 0;
        }
        for (i = 0; i < n; i++) puts(res[i]);
    }
    return 0;
}

 

Cavity Map HackerRank Solution in C++

#include <bits/stdc++.h>

using namespace std;

int N;
char grid[101][101];
char grid2[101][101];

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;
}

 

Cavity Map HackerRank Solution in Java

import java.util.*;
class Solution
    {
        public static void main(String ar[])
            {
                Scanner in=new Scanner(System.in);
                int n=in.nextInt(),i,j;
                char c[][]=new char[n][];
                for(i=0;i<n;i++)
                    {
                        c[i]=in.next().toCharArray();
                    }
                for(i=1;i<n-1;i++)                
                    {
                        for(j=1;j<n-1;j++)
                            {
                                if(c[i][j]>c[i][j-1] && c[i][j]>c[i][j+1] && c[i][j]>c[i-1][j] && c[i][j]>c[i+1][j])
                                    c[i][j]='X';
                            }
                    }
                for(i=0;i<n;i++)
                    System.out.println(new String(c[i]));
            }
    }

 

Cavity Map HackerRank Solution in Python

import sys

n = int(sys.stdin.readline())

m = []

for ix in range(n):
    l = sys.stdin.readline()
    if l[-1] == '\n':
        l = l[:-1]
    m.append([int(c) for c in l])

m2 = [[c for c in l] for l in m]

ds = [(-1, 0), (1, 0), (0, -1), (0, 1)]

for x in range(1, n - 1):
    for y in range(1, n - 1):
        v = m[x][y]
        if all(map(lambda z: m[x + z[0]][y + z[1]] < v, ds)):
            m2[x][y] = 'X'

for l in m2:
    print ''.join(map(str, l))

 

Cavity Map HackerRank Solution in C#

using System;
using System.Linq;
public class Test
{
    public static void Main()
    {
        // your code goes here
        int n = int.Parse(Console.ReadLine());
        int[,] num = new int[n,n];
        for(int i = 0 ; i < n ; i++){
            string str = Console.ReadLine().Trim();
            for(int j = 0 ; j < n ; j++){
                int x = int.Parse(str[j].ToString());
                num[i,j] = x;
            }
        }
       string output = string.Empty;
        for(int i = 0 ; i < n ; i++){
            output = string.Empty;
            for(int j = 0 ; j < n ; j++){
                if(i == 0 || j == 0 || i == n - 1 || j == n-1)
                     output += num[i,j];
                 else {
                 	if(num[i-1,j] < num[i,j] && num[i+1,j] < num[i,j] && num[i,j+1] < num[i,j] && num[i,j-1] < num[i,j]){
                 		output += "X";
                 	}else{
                 		output += num[i,j];
                 	}
                 }
            }
            Console.WriteLine(output);
        }
        
    }
}

 

Attempt Cavity Map HackerRank Challenge

Link –¬†https://www.hackerrank.com/challenges/cavity-map/

Next HackerRank Challenge Solution 

Link –¬†https://exploringbits.com/the-grid-search-hackerrank-solution/

Leave a Comment