Skip to content

Cavity Map

MoustafaAttia edited this page Nov 29, 2017 · 2 revisions

This wiki to show my solution for HackerRank problem Cavity Map

Solution steps:

  • While problem state that cell must not in the border, so first step is add the first row as is
  • looping over each row 1 to row n-1 (0-based indexing)
  • in each iteration I add the first and last cell as is, the same reason as first point
  • then for each cell inside loop check for 4-adjacent cells if they all are smaller than current cell, then append ‘X’
  • Finally add the last row as is (row n-1), also for the same reason as first point

Solution in Python 3:

import sys

n = int(input().strip())
grid = []
grid_i = 0
for grid_i in range(n):
    grid_t = str(input().strip())
    grid.append(grid_t)
    
gridRes = []
gridRes.append(grid[0])
if n == 1:
    print (grid[0][0])
else:
    for g in range(1,n-1):
        line = grid[g][0]
        for i in range(1,n-1):
            if grid[g][i-1]< grid[g][i] and grid[g][i+1] < grid[g][i] and grid[g+1][i] < grid[g][i] and grid[g-1][i] < grid[g][i]:
                    line += "X"
            else:
                line += grid[g][i]
        line += grid[g][n-1]
        gridRes.append(line)
                
            
    gridRes.append(grid[n-1])
    for g in gridRes:
        print(g)

Clone this wiki locally