Categories
Python: Dominant Cells
Date
Author
There is a given list of lists of integers that represent a 2-dimensional grid with n rows and m columns. A cell is called a dominant cell if it has a strictly greater value than all of its neighbors. Two cells are neighbors when they share a common side or a common corner, so a cell can have up to 8 neighbors. Find the number of dominant cells in the grid.
Function Description
Complete the function numCells in the editor below.
numCells has the following parameter(s):
int grid[n][m]: a 2-dimensional array of integers
Returns
int: the number of dominant cells in the grid
Constraints
- 1 ≤ n, m ≤ 500
- There are at least 2 cells in the grid.
- 1 ≤ grid[i][j] ≤ 100
SOLUTION:
#!/bin/python3
import math
import os
import random
import re
import sys
def numCells(grid):
n = len(grid)
m = len(grid[0])
count = 0
for i in range(n):
for j in range(m):
cell_value = grid[i][j]
is_dominant = True
for ni in range(max(0, i - 1), min(n, i + 2)):
for nj in range(max(0, j - 1), min(m, j + 2)):
if ni != i or nj != j:
if grid[ni][nj] >= cell_value:
is_dominant = False
break
if not is_dominant:
break
if is_dominant:
count += 1
return count
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
grid_rows = int(input().strip())
grid_columns = int(input().strip())
grid = []
for _ in range(grid_rows):
grid.append(list(map(int, input().rstrip().split())))
result = numCells(grid)
fptr.write(str(result) + '\n')
fptr.close()