Last active
February 7, 2023 01:07
-
-
Save webdevwilson/6eac5192dbfbb8019a06b7e3cc694b8d to your computer and use it in GitHub Desktop.
This file contains hidden or 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
#!/usr/bin/env python3 | |
TEST = [ | |
[0, 0, 0, 1, 0, 0, 0], | |
[0, 1, 0, 1, 1, 1, 0], | |
[0, 0, 1, 1, 0, 1, 0], | |
[0, 1, 1, 0, 0, 1, 0], | |
[0, 1, 0, 0, 1, 1, 1], | |
[0, 1, 1, 0, 0, 1, 1], | |
[0, 1, 0, 0, 1, 1, 1], | |
] | |
NUM_ROWS = len(TEST) | |
NUM_COLS = len(TEST[0]) | |
# Validate our data structure | |
assert NUM_ROWS == NUM_COLS, 'Number of rows must equal number of columns' | |
for _ in TEST: | |
assert NUM_COLS == len(_), 'Row column mismatch' | |
def calculate_tree_depth(row, col: int, path: list[int]): | |
# Don't check if current node is 0 | |
if not TEST[row][col]: | |
return 0 | |
neighbors = [(row - 1, col), (row, col - 1), (row, col + 1), (row + 1, col)] | |
path.append((row, col)) | |
max_neighbor_depth = 0 | |
print(path) | |
for r, c in neighbors: | |
if 0 <= r < NUM_ROWS and 0 <= c < NUM_COLS and (r, c) not in path: # stay in bounds and don't loop on a path | |
max_neighbor_depth = max(max_neighbor_depth, calculate_tree_depth(r, c, path.copy())) | |
return max_neighbor_depth + 1 | |
# Iterate over all elements | |
max_depth = 0 | |
for i in range(0, NUM_ROWS): | |
for j in range(0, NUM_COLS): | |
max_depth = max(max_depth, calculate_tree_depth(i, j, [])) | |
print(f'Max: {max_depth}') | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment