Problem 1210

Abstract / Summary

Find the least moves to reach a target point on a grid by moving or rotating direction each turn.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1210.py

class Solution:
    def minimumMoves(self, grid: List[List[int]]) -> int:
        size = len(grid)

        done = set()

        todo  = [ ( 1, 0, 0, 0 ) ] # (headx, heady, tailx, taily)
        steps = 0
        # straight-forward breadth-first search
        while todo:
            next = set()

            for snake in todo:
                # skip already known positions
                if snake in done:
                    continue
                done.add(snake)

                x, y, x2, y2 = snake

                # done
                if x == size - 1 and y == size - 1 and y == y2: # snake must be horizontal, too
                    return steps

                # too far right / down
                if x == size or y == size:
                    continue

                # helper function:
                # check if valid move, then add to list
                def add(x, y, x2, y2):
                    if 0 <= x < size and 0 <= y < size:
                        if grid[y][x] == 0 and grid[y2][x2] == 0:
                            next.add(( x, y, x2, y2 ))

                # move right
                add(x + 1, y, x2 + 1, y2)
                # move down
                add(x, y + 1, x2, y2 + 1)
                # rotate (x2 and y2 stay the same, but x2+1, y2+1 must be empty, too)
                if y2 + 1 < size and x2 + 1 < size and grid[y2 + 1][x2 + 1] == 0:
                    if y == y2:
                        # horizontal => vertical
                        add(x - 1, y + 1, x2, y2)
                    else:
                        # vertical   => horizontal
                        add(x + 1, y - 1, x2, y2)

            todo   = next
            steps += 1

        # running out of moves before reaching final position
        return -1
53 lines | 1836 bytes | submitted March 14, 2024 | GitHub   45% comment ratio | tab size 4 | moderate complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 53% (20k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Breadth First Search
  • Matrix
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation solves the classic “minimum moves for a snake” problem on a square grid. It treats the snake as a two-cell segment that can slide right, slide down, or rotate about one of its ends. By exploring reachable configurations with a breadth-first search (BFS), the algorithm returns the smallest number of moves required to place the snake horizontally in the bottom-right corner, or -1 if the goal cannot be reached.

Core Data Structures

The grid dimension is captured in size. A set named done records every snake configuration that has already been processed, guaranteeing that each state is examined at most once. The frontier of the BFS is stored in todo, initially containing the starting configuration (1, 0, 0, 0), which represents a horizontal snake whose head is at column 1, row 0 and tail at column 0, row 0. The integer steps counts how many BFS layers have been expanded.

size = len(grid)
done = set()
todo  = [ (1, 0, 0, 0) ]          # (headx, heady, tailx, taily)
steps = 0

BFS Loop

The outer while loop continues until there are no more configurations to explore. For each layer a fresh set next is created; it automatically eliminates duplicate states generated within the same layer. After processing all snakes in todo, the algorithm swaps todo with next and increments steps.

while todo:
    next = set()
    for snake in todo:
        ...
    todo   = next
    steps += 1

State Representation

Each snake is encoded as a four-tuple (headx, heady, tailx, taily). The orientation is implicit: when heady == taily the snake lies horizontally, otherwise it is vertical. Unpacking the tuple makes the coordinates readily available for subsequent checks.

x, y, x2, y2 = snake

Goal Check

The algorithm terminates successfully when the head reaches the bottom-right cell (size-1, size-1) and the snake is horizontal (y == y2). This condition guarantees that both cells of the snake occupy the final two positions in the last row.

if x == size - 1 and y == size - 1 and y == y2:
    return steps

Boundary Checks

Before attempting any move, the code discards configurations that have already stepped outside the grid. If either the head’s column or row equals size, the configuration is ignored because it would be off-grid.

if x == size or y == size:
    continue

Move Generation Helper

A small inner function add encapsulates the validation logic for a prospective new configuration. It first checks that the new head coordinates lie inside the grid, then verifies that both the head and tail cells are free (grid[y][x] == 0 and grid[y2][x2] == 0). Valid configurations are inserted into the next set.

def add(x, y, x2, y2):
    if 0 <= x < size and 0 <= y < size:
        if grid[y][x] == 0 and grid[y2][x2] == 0:
            next.add((x, y, x2, y2))

Moves: Right, Down, Rotation

Slide Right

Both head and tail advance one column to the right. The helper ensures the new cells are inside the grid and unblocked.

add(x + 1, y, x2 + 1, y2)

Slide Down

Both head and tail move one row downward, again guarded by the helper.

add(x, y + 1, x2, y2 + 1)

Rotation

A rotation pivots the snake around its tail. The code first confirms that the cell diagonally adjacent to the tail (grid[y2 + 1][x2 + 1]) is empty, which is required for the rotating segment to occupy. If the snake is currently horizontal (y == y2), the rotation yields a vertical orientation by moving the head up-left; otherwise a vertical snake becomes horizontal by moving the head down-right. The helper validates the resulting positions.

if y2 + 1 < size and x2 + 1 < size and grid[y2 + 1][x2 + 1] == 0:
    if y == y2:                     # horizontal → vertical
        add(x - 1, y + 1, x2, y2)
    else:                           # vertical → horizontal
        add(x + 1, y - 1, x2, y2)

Edge Cases Handled

The implementation gracefully deals with several boundary conditions. When the snake reaches the rightmost column or the bottom row, the early boundary check prevents out-of-range indexing. Rotations are only attempted if the diagonal cell next to the tail exists (y2 + 1 < size and x2 + 1 < size) and is free, thereby avoiding illegal pivots near the grid edges. The goal condition explicitly requires the snake to be horizontal, ensuring that configurations where the head is at the target cell but the snake is vertical are not mistakenly accepted. Obstacles are respected throughout because every candidate move validates both head and tail cells against the grid values.

Performance Optimizations

The algorithm employs a set done to remember every processed configuration, eliminating redundant work and guaranteeing termination even in the presence of cycles. Using a set for the next frontier (next) automatically collapses duplicate states generated by different move sequences within the same BFS layer, reducing the number of enqueued items. The inner helper add centralizes validation, avoiding repeated code and keeping the per-move overhead low. By checking the goal condition immediately after dequeuing a state, the search can stop at the earliest possible moment, preventing unnecessary expansion of deeper layers. The overall structure-layer-by-layer BFS with constant-time set operations-ensures that the exploration proceeds efficiently across the state space.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a long, bendy toy snake lying on a grid of square tiles. The goal is to get the snake to the bottom right corner of the grid, but the snake has to wiggle through empty spaces without touching any blocks.

The code starts by keeping track of where the snake is currently resting. It saves every position the snake visits in a special memory pile so that it does not get stuck going in circles. The main part of the code looks at the snake and thinks about every possible move, such as sliding to the right, sliding down, or carefully spinning around a corner.

Each time the snake makes a move, the code counts it as one step. It keeps exploring all the paths at the same time, making sure each new spot is empty and safe for the snake to be. This continues until the snake finally curls into the target spot at the end of the grid. If the snake ever reaches a point where it cannot move anymore or gets stuck before reaching the finish, the process stops.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 6 | μ = 5.81 | σ = 1.42

Complexity Analysis

Time: polynomial
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ JS Python Java Go TS
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
everthis JS
fsq C++
JoshCrozier JS
lkwq007 Python
suxrobGM C#
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, JavaScript, Python, TypeScript
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fsq C++
JoshCrozier JavaScript
lkwq007 Python
suxrobGM C#
23 links | 11 authors | 7 languages

Solved On The Same Day

2 solutions   March 14, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality