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.

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!

#### Latest posts by Sidharth Patnaik (see all)

- NATASHA: AI assistant using Raspberry Pi - October 26, 2017
- Hackerrank Modified Kaprekar Numbers Solution - October 31, 2015
- My First webpage using Bootstrap Framework - October 29, 2015