Created
December 4, 2020 20:05
-
-
Save falseresync/3a2245c1fa22521aca202189e2917083 to your computer and use it in GitHub Desktop.
DFS power grid net average
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
0 0 0 0 0 0 -3 0 0 | |
0 0 0 0 0 0 x 0 0 | |
0 0 x x x x x x 2 | |
0 0 x 0 x 0 x 0 0 | |
0 0 x 0 x x x x 2 | |
-3 x x 0 0 x 0 0 0 | |
0 0 x x x x 0 0 0 | |
0 0 0 0 0 3 0 0 0 |
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
from typing import List, Tuple | |
def read_data(path: str) -> List[List[str]]: | |
data = [] | |
with open(path, 'r') as f: | |
for line in f.readlines(): | |
data.append(line.split(' ')) | |
return data | |
def netPower(data: List[List[str]], traversed: List[Tuple[int, int]]) -> int: | |
netPower = 0 | |
for row, col in traversed: | |
item = data[row][col] | |
if item != 'x': | |
netPower += int(item) | |
return netPower | |
def traverse(data: List[List[str]], startingRow: int, startingCol: int) -> set: | |
queue = [(startingRow, startingCol)] | |
visited = set() | |
while len(queue) > 0: | |
row, col = queue.pop(0) | |
visited.add((row, col)) | |
for row, col in neighbors(data, row, col): | |
if (row, col) not in visited: | |
queue.append((row, col)) | |
return visited | |
def neighbors(data: List[List[str]], row: int, col: int) -> List[Tuple[int, int]]: | |
indices = [(row + 1, col), (row - 1, col), (row, col + 1), (row, col - 1)] | |
colLen = len(data) | |
rowLen = len(data[0]) | |
return [(row, col) for row, col in indices if row >= 0 and col >= 0 and row < colLen and col < rowLen and data[row][col] != '0'] | |
if __name__ == '__main__': | |
data = read_data('data.txt') | |
print(netPower(data, traverse(data, 4, 4))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment