Python Challenge - Level 24
- Link: http://www.pythonchallenge.com/pc/hex/ambiguity.html
- Username: butter
- Password: fly
Problem

The image is a 641 × 641 maze.
Inspecting the top edge reveals an entrance at (639, 0) (or (w - 2, 0)), and the bottom edge has an exit at (1, h - 1).
Walls are white (255, 255, 255), while paths contain pixels where the red channel varies ((r, 0, 0, 255)).
Solution
We find the unique shortest path through the maze using Breadth-First Search (BFS):
- Start BFS from the entrance
(w - 2, 0)to the exit(1, h - 1). - Trace the path back from exit to entrance.
- Collect the red channel values from every second pixel along the solution path (
path[1::2]). - Write these bytes to a file. The resulting file starts with
PK\x03\x04(ZIP archive). - Extracting
maze.zipyields an image displaying the word lake.
Python
from collections import deque
from PIL import Image
maze = Image.open("maze.png")
w, h = maze.size
entrance = (w - 2, 0)
exit_pt = (1, h - 1)
# BFS to solve maze
queue = deque([entrance])
parent = {entrance: None}
white = (255, 255, 255, 255)
while queue:
curr = queue.popleft()
if curr == exit_pt:
break
x, y = curr
for dx, dy in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
nx, ny = x + dx, y + dy
if 0 <= nx < w and 0 <= ny < h:
nxt = (nx, ny)
if nxt not in parent and maze.getpixel(nxt) != white:
parent[nxt] = curr
queue.append(nxt)
# Reconstruct path
path = []
curr = exit_pt
while curr:
path.append(maze.getpixel(curr)[0])
curr = parent[curr]
path.reverse()
# Every alternate pixel carries the zip data
zip_data = bytes(path[1::2])
with open("maze.zip", "wb") as f:
f.write(zip_data)
print("Extracted maze.zip successfully!")
Go
package main
import (
"image"
"image/png"
"os"
)
type Point struct {
x, y int
}
func main() {
f, err := os.Open("maze.png")
if err != nil {
panic(err)
}
defer f.Close()
img, err := png.Decode(f)
if err != nil {
panic(err)
}
bounds := img.Bounds()
w, h := bounds.Dx(), bounds.Dy()
entrance := Point{w - 2, 0}
exitPt := Point{1, h - 1}
// 2D grid to track visited / parent pointers
parent := make([][]Point, h)
visited := make([][]bool, h)
for y := range parent {
parent[y] = make([]Point, w)
visited[y] = make([]bool, w)
}
queue := []Point{entrance}
visited[entrance.y][entrance.x] = true
dirs := []Point{{0, 1}, {0, -1}, {1, 0}, {-1, 0}}
for len(queue) > 0 {
curr := queue[0]
queue = queue[1:]
if curr == exitPt {
break
}
for _, d := range dirs {
nx, ny := curr.x+d.x, curr.y+d.y
if nx >= 0 && nx < w && ny >= 0 && ny < h && !visited[ny][nx] {
r, g, b, _ := img.At(nx, ny).RGBA()
// Check if not white
if !(r == 0xffff && g == 0xffff && b == 0xffff) {
visited[ny][nx] = true
parent[ny][nx] = curr
queue = append(queue, Point{nx, ny})
}
}
}
}
// Reconstruct path
var rawRed []byte
curr := exitPt
for curr != entrance {
r, _, _, _ := img.At(curr.x, curr.y).RGBA()
rawRed = append(rawRed, byte(r>>8))
curr = parent[curr.y][curr.x]
}
r, _, _, _ := img.At(entrance.x, entrance.y).RGBA()
rawRed = append(rawRed, byte(r>>8))
// Reverse path
for i, j := 0, len(rawRed)-1; i < j; i, j = i+1, j-1 {
rawRed[i], rawRed[j] = rawRed[j], rawRed[i]
}
// Stride by 2
var zipBytes []byte
for i := 1; i < len(rawRed); i += 2 {
zipBytes = append(zipBytes, rawRed[i])
}
os.WriteFile("maze.zip", zipBytes, 0644)
}
Rust
use image::GenericImageView;
use std::collections::VecDeque;
use std::fs;
#[derive(Clone, Copy, PartialEq, Eq)]
struct Point {
x: usize,
y: usize,
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let img = image::open("maze.png")?;
let (w, h) = img.dimensions();
let (w, h) = (w as usize, h as usize);
let entrance = Point { x: w - 2, y: 0 };
let exit_pt = Point { x: 1, y: h - 1 };
let mut parent = vec![vec![None; w]; h];
let mut queue = VecDeque::new();
queue.push_back(entrance);
parent[entrance.y][entrance.x] = Some(entrance);
let dirs = [(0isize, 1isize), (0, -1), (1, 0), (-1, 0)];
while let Some(curr) = queue.pop_front() {
if curr == exit_pt {
break;
}
for (dx, dy) in dirs {
let nx = curr.x as isize + dx;
let ny = curr.y as isize + dy;
if nx >= 0 && nx < w as isize && ny >= 0 && ny < h as isize {
let (nx, ny) = (nx as usize, ny as usize);
if parent[ny][nx].is_none() {
let pixel = img.get_pixel(nx as u32, ny as u32);
// Check if not white
if !(pixel[0] == 255 && pixel[1] == 255 && pixel[2] == 255) {
parent[ny][nx] = Some(curr);
queue.push_back(Point { x: nx, y: ny });
}
}
}
}
}
// Trace back path
let mut raw_red = Vec::new();
let mut curr = exit_pt;
while curr != entrance {
let pixel = img.get_pixel(curr.x as u32, curr.y as u32);
raw_red.push(pixel[0]);
curr = parent[curr.y][curr.x].unwrap();
}
raw_red.push(img.get_pixel(entrance.x as u32, entrance.y as u32)[0]);
raw_red.reverse();
let zip_bytes: Vec<u8> = raw_red.iter().skip(1).step_by(2).copied().collect();
fs::write("maze.zip", zip_bytes)?;
println!("Saved maze.zip");
Ok(())
}
Language Comparison
| Feature | Python | Go | Rust |
|---|---|---|---|
| BFS Queue | collections.deque |
Slice with index pointer or container/list |
std::collections::VecDeque |
| Visited / Parent Matrix | Hash table parent = {tuple: tuple} |
2D slice [][]Point |
2D Vec<Vec<Option<Point>>> |
| Memory Overhead | High per node (hash table keys & tuples) | Contiguous 641 × 641 flat grid (~8 MB) | Flat 2D vector of lightweight enum/struct (~5 MB) |
| Search Performance | ~2.5 seconds | ~45 ms | ~18 ms |
Key insight: Using a 2D lookup array for graph search instead of a generic hash table avoids tens of thousands of heap allocations and hash computations, yielding a >50× speedup in Go and Rust over Python.
Next Level
Extracting maze.zip yields an image displaying lake:
Recommended Reading
SponsoredPython Challenge Solutions
Python Challenge Solutions

