76 lines
2.1 KiB
Python
76 lines
2.1 KiB
Python
|
def count_guard_positions(map_lines):
|
||
|
# Convert the map to a mutable 2D list of characters
|
||
|
grid = [list(row) for row in map_lines]
|
||
|
rows, cols = len(grid), len(grid[0])
|
||
|
|
||
|
# Directions: UP=0, RIGHT=1, DOWN=2, LEFT=3
|
||
|
directions = [(-1, 0), (0, 1), (1, 0), (0, -1)]
|
||
|
|
||
|
# Find the initial guard position '^'
|
||
|
start_pos = None
|
||
|
for r in range(rows):
|
||
|
for c in range(cols):
|
||
|
if grid[r][c] == '^':
|
||
|
start_pos = (r, c)
|
||
|
grid[r][c] = '.' # Replace '^' with '.'
|
||
|
break
|
||
|
if start_pos:
|
||
|
break
|
||
|
|
||
|
# Initialize guard state
|
||
|
current_pos = start_pos
|
||
|
current_dir = 0 # Start facing UP
|
||
|
visited = {current_pos}
|
||
|
steps = 0
|
||
|
|
||
|
# Large safety limit to prevent infinite loops in case something goes wrong
|
||
|
max_steps = rows * cols * 10
|
||
|
|
||
|
while True:
|
||
|
steps += 1
|
||
|
if steps > max_steps:
|
||
|
# If something is wrong, break out to avoid infinite loop
|
||
|
print("Exceeded maximum expected steps. Stopping.")
|
||
|
break
|
||
|
|
||
|
# Calculate the next forward position
|
||
|
dr, dc = directions[current_dir]
|
||
|
next_r = current_pos[0] + dr
|
||
|
next_c = current_pos[1] + dc
|
||
|
|
||
|
# Check if moving forward would leave the grid
|
||
|
if not (0 <= next_r < rows and 0 <= next_c < cols):
|
||
|
# The guard leaves the mapped area here
|
||
|
break
|
||
|
|
||
|
# Check if the next cell is an obstacle
|
||
|
if grid[next_r][next_c] == '#':
|
||
|
# Can't move forward, turn right
|
||
|
current_dir = (current_dir + 1) % 4
|
||
|
continue
|
||
|
|
||
|
# The next cell is free, move forward
|
||
|
current_pos = (next_r, next_c)
|
||
|
visited.add(current_pos)
|
||
|
# Continue forward in the same direction on the next iteration
|
||
|
|
||
|
return len(visited)
|
||
|
|
||
|
|
||
|
# Given example grid
|
||
|
example_grid = [
|
||
|
"....#.....",
|
||
|
".........#",
|
||
|
"..........",
|
||
|
"..#.......",
|
||
|
".......#..",
|
||
|
"..........",
|
||
|
".#.^......",
|
||
|
"........#.",
|
||
|
"#.........",
|
||
|
"......#..."
|
||
|
]
|
||
|
|
||
|
result = count_guard_positions(example_grid)
|
||
|
print("Result:", result)
|