Hackerrank Cavity Map Solution

This is the solution to the Cavity Map problem found in the the implementation section of the Algorithm domain in Hackerrank. The bellow solution is in Python2. In this you are given a square map of size n×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.

Screenshot:


The Code:
def mapCavity(arr, n):
    for i in range(1, n-1):
        for j in range(1, n-1):
            if arr[i-1][j] != 'X' and int(arr[i-1][j]) < int(arr[i][j]) and \
                arr[i+1][j] != 'X' and int(arr[i+1][j]) < int(arr[i][j]) and \
                arr[i][j-1] != 'X' and int(arr[i][j-1]) < int(arr[i][j]) and \
                arr[i][j+1] != 'X' and int(arr[i][j+1]) < int(arr[i][j]):
                    arr[i][j] = 'X'
n = input()
arr = []
for k in range(n):
    line = list(raw_input())
    arr.append(line)
mapCavity(arr, n)
for line in arr:
    print ''.join(line)
Found bugs, got questions ?
Do comment them here !

Comments

Popular posts from this blog

Non Restoring Division Algorithm Implementation in C

Employee Management System Using Inheritance in Java

Bit Stuffing Code Implementation in Java