#!/bin/python3 import sys,time,re from pprint import pprint sys.path.insert(0, '../../') from fred import list2int,get_re,nprint,lprint,loadFile,toGrid,TSP,dijkstra,bfs,get_value_in_direction,addTuples start_time = time.time() input_f = 'input' grid = toGrid(input_f,list2int) directions = [(-1,0),(1,0),(0,1),(0,-1)] starts = [] ends = [] # Get coordinates of all start points (0) and all end points (9) for row in range(len(grid)): for col in range(len(grid[row])): if grid[row][col] == 0: starts.append((row,col)) elif grid[row][col] == 9: ends.append((row,col)) # If the current node is in the list of end nodes, return it. def is_goal(node): return node in ends # Get the neighbors of the current node. def get_neighbors(node): directions = ['up','down','left','right'] offsets = { 'up': (-1, 0), 'down': (1, 0), 'left': (0, -1), 'right': (0, 1), } neighbors = [] # Loop through all the directions for d in directions: t = get_value_in_direction(grid,node) # If the direction is 1 more than the current nodes value, # add it to the list of valid neighbors. if get_value_in_direction(grid,node,d) == t+1: neighbors.append(addTuples(offsets[d],node)) # Return the list of valid neighbors return neighbors result = 0 # Loop through all the starting points. for s in starts: # Call a standard BFS (Breadth First Search). # Takes the following inputs: # s: Starting node # is_goal: function that returns true if the current node is the goal # get_neighbors: returns a list of valid neighbors # Returns a list of all visited goals and the path to the goals. goal_nodes, paths_to_goal = bfs(s,is_goal,get_neighbors) # We onlu care about how many goals each starting position reached. result += len(goal_nodes) print(result) print("--- %s seconds ---" % (time.time() - start_time))