-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add solution for find the most adjacent int of same values
- Loading branch information
1 parent
efb3278
commit 80d59c7
Showing
1 changed file
with
32 additions
and
0 deletions.
There are no files selected for viewing
32 changes: 32 additions & 0 deletions
32
src/python/katas/py5kyu/find_the_most_adjacent_integers_of_the_same_value_in_a_grid.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
"""Kata url: https://www.codewars.com/kata/5b258cf6d74b5b7105000035.""" | ||
|
||
def flood(grid, x, y, target) -> int: | ||
if x < 0 or x >= len(grid[0]): | ||
return 0 | ||
if y < 0 or y >= len(grid): | ||
return 0 | ||
if grid[y][x] != target: | ||
return 0 | ||
|
||
grid[y][x] = -1 | ||
return 1 + sum( | ||
flood(grid, x + dx, y + dy, target) | ||
for dx, dy in ((-1,0), (1,0), (0,-1), (0,1)) | ||
) | ||
|
||
|
||
def find_most_adjacent(grid): | ||
bv, bc = (-1, 0) | ||
|
||
for y, line in enumerate(grid): | ||
for x, cell in enumerate(line): | ||
if cell == -1: | ||
continue | ||
|
||
count = flood(grid, x, y, cell) | ||
if count > bc: | ||
bv, bc = (cell, count) | ||
elif count == bc and cell < bv: | ||
bv = cell | ||
|
||
return bv, bc |