#!/usr/bin/env python3
# -*- coding: utf-8 -*-

file = "./input.txt"
XY_DIMENSION = 70
FIRST_BYTES = 1024


#file = "./ex.txt"
#XY_DIMENSION = 6
#FIRST_BYTES = 12

from time import time
start_time = time()

def make_empty_grid(dimension:int)->list[list[str]]:
    result = []
    for _ in range(dimension+1):
        result.append(["." for _ in range(dimension+1)])
    return result

def print_grid(f):
    for r in f:
        for s in r:
            if s == 0:
                print(".", end="")
            else:
                print(s, end="")
        print()

def fill_grid(gri:list[list[str]], ma:list[list[int]], filler:str)->list[list[str]]:
    for m in ma:
        x , y = m[0],m[1]
        gri[y][x] = filler
    return gri

def read_input(input_file:str, ) -> list[list[int]]:
    out = []
    f = open(input_file, "r")
    for line in f:
        line = line.strip()
        if line == "":
            continue
        else:
            out.append(list(map(int,line.split(','))))
    f.close()
    return out
from collections import deque

def shortest_path(array, start, end):
    zeilen, spalten = len(array), len(array[0])
    visited = set()
    queue = deque([(start, [start])])
    while queue:
        (x, y), pfad = queue.popleft()
        if (x, y) == end:
            return len(pfad) - 1, pfad
        for dx, dy in [(0, 1), (1, 0), (0, -1), (-1, 0)]:
            nx, ny = x + dx, y + dy
            if 0 <= nx < zeilen and 0 <= ny < spalten and array[nx][ny] == '.' and (nx, ny) not in visited:
                queue.append(((nx, ny), pfad + [(nx, ny)]))
                visited.add((nx, ny))

    return -1, []  # Kein Pfad gefunden


if __name__ == "__main__":
    grid = make_empty_grid(XY_DIMENSION)
    corrupted = read_input(file)
    for i in range(FIRST_BYTES, len(corrupted)):
        if shortest_path(fill_grid(grid,corrupted[:i],"#"),(0,0),(XY_DIMENSION,XY_DIMENSION))[0] == -1:
            print(f"First Blocking Field: {corrupted[:i][-1]}")
            break
    print(f'Runtime: {time()-start_time:.4f} s')