#!/usr/bin/env python3
# -*- coding: utf-8 -*-
file = "./input.txt"
#file = "./ex.txt"
import sys
sys.setrecursionlimit(6000)

def print_game_field():
    for game_line in game_field:
        print(game_line)

def guard_position() -> (int, int):
    for li in range(game_field_lines):
        for ro in range(game_field_rows):
            if game_field[li][ro] == '^':
                print(f'GuardPosition: line:{li}, row:{ro}')
                return li, ro

def go_up():
    global gl
    global gr
    game_field[gl][gr] = 'X'
    if gl == 0:
        count_fields()
    elif game_field[gl-1][gr] == '#':
        go_right()
    else:
        gl -= 1
        go_up()

def go_right():
    global gl
    global gr
    game_field[gl][gr] = 'X'
    if gr == game_field_rows-1:
        count_fields()
    elif game_field[gl][gr+1] == '#':
        go_down()
    else:
        gr += 1
        go_right()

def go_down():
    global gl
    global gr
    game_field[gl][gr] = 'X'
    if gl == game_field_lines-1:
        count_fields()
    elif game_field[gl+1][gr] == '#':
        go_left()
    else:
        gl += 1
        go_down()

def go_left():
    global gl
    global gr
    game_field[gl][gr] = 'X'
    if gr == 0:
        count_fields()
    elif game_field[gl][gr-1] == '#':
        go_up()
    else:
        gr -= 1
        go_left()

def count_fields():
    solution = 0
    for g_line in game_field:
        for field in g_line:
            if field == 'X':
                solution += 1
    print_game_field()
    print("Ende")
    print(f"Number of visited Fields: {solution}")
    exit(0)

if __name__ == "__main__":
    game_field = []
    input_file = open(file, "r")
    for line in input_file:
        line = line.strip()
        if line == "":
            continue
        tmp = []
        for b in line:
            tmp.append(b)
        game_field.append(tmp)
    input_file.close()

print_game_field()
game_field_lines, game_field_rows = len(game_field), len(game_field[0])
gl, gr = guard_position()
go_up()
