LeetCode #3665 — MEDIUM

Twisted Mirror Path Count

Move from brute-force thinking to an efficient approach using array strategy.

Solve on LeetCode
The Problem

Problem Statement

Given an m x n binary grid grid where:

  • grid[i][j] == 0 represents an empty cell, and
  • grid[i][j] == 1 represents a mirror.

A robot starts at the top-left corner of the grid (0, 0) and wants to reach the bottom-right corner (m - 1, n - 1). It can move only right or down. If the robot attempts to move into a mirror cell, it is reflected before entering that cell:

  • If it tries to move right into a mirror, it is turned down and moved into the cell directly below the mirror.
  • If it tries to move down into a mirror, it is turned right and moved into the cell directly to the right of the mirror.

If this reflection would cause the robot to move outside the grid boundaries, the path is considered invalid and should not be counted.

Return the number of unique valid paths from (0, 0) to (m - 1, n - 1).

Since the answer may be very large, return it modulo 109 + 7.

Note: If a reflection moves the robot into a mirror cell, the robot is immediately reflected again based on the direction it used to enter that mirror: if it entered while moving right, it will be turned down; if it entered while moving down, it will be turned right. This process will continue until either the last cell is reached, the robot moves out of bounds or the robot moves to a non-mirror cell.

Example 1:

Input: grid = [[0,1,0],[0,0,1],[1,0,0]]

Output: 5

Explanation:

Number Full Path
1 (0, 0) → (0, 1) [M] → (1, 1) → (1, 2) [M] → (2, 2)
2 (0, 0) → (0, 1) [M] → (1, 1) → (2, 1) → (2, 2)
3 (0, 0) → (1, 0) → (1, 1) → (1, 2) [M] → (2, 2)
4 (0, 0) → (1, 0) → (1, 1) → (2, 1) → (2, 2)
5 (0, 0) → (1, 0) → (2, 0) [M] → (2, 1) → (2, 2)
  • [M] indicates the robot attempted to enter a mirror cell and instead reflected.

Example 2:

Input: grid = [[0,0],[0,0]]

Output: 2

Explanation:

Number Full Path
1 (0, 0) → (0, 1) → (1, 1)
2 (0, 0) → (1, 0) → (1, 1)

Example 3:

Input: grid = [[0,1,1],[1,1,0]]

Output: 1

Explanation:

Number Full Path
1 (0, 0) → (0, 1) [M] → (1, 1) [M] → (1, 2)
(0, 0) → (1, 0) [M] → (1, 1) [M] → (2, 1) goes out of bounds, so it is invalid.

Constraints:

  • m == grid.length
  • n == grid[i].length
  • 2 <= m, n <= 500
  • grid[i][j] is either 0 or 1.
  • grid[0][0] == grid[m - 1][n - 1] == 0
Patterns Used

Roadmap

  1. Brute Force Baseline
  2. Core Insight
  3. Algorithm Walkthrough
  4. Edge Cases
  5. Full Annotated Code
  6. Interactive Study Demo
  7. Complexity Analysis
Step 01

Brute Force Baseline

Problem summary: Given an m x n binary grid grid where: grid[i][j] == 0 represents an empty cell, and grid[i][j] == 1 represents a mirror. A robot starts at the top-left corner of the grid (0, 0) and wants to reach the bottom-right corner (m - 1, n - 1). It can move only right or down. If the robot attempts to move into a mirror cell, it is reflected before entering that cell: If it tries to move right into a mirror, it is turned down and moved into the cell directly below the mirror. If it tries to move down into a mirror, it is turned right and moved into the cell directly to the right of the mirror. If this reflection would cause the robot to move outside the grid boundaries, the path is considered invalid and should not be counted. Return the number of unique valid paths from (0, 0) to (m - 1, n - 1). Since the answer may be very large, return it modulo 109 + 7. Note: If a reflection moves the robot

Baseline thinking

Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.

Pattern signal: Array · Dynamic Programming

Example 1

[[0,1,0],[0,0,1],[1,0,0]]

Example 2

[[0,0],[0,0]]

Example 3

[[0,1,1],[1,1,0]]
Step 02

Core Insight

What unlocks the optimal approach

  • Precompute, for each cell and each move (right/down), where you actually land if there’s a mirror next—store these "jump" targets in a <code>go[i][j][0/1]</code> table.
  • Let <code>dp[i][j]</code> = number of ways to reach (i,j); set <code>dp[0][0] = 1</code>, then scan cells in row‑major order and for each <code>dp[i][j] > 0</code> add <code>dp[i][j]</code> into <code>dp[x][y]</code> for both precomputed moves.
  • Always take additions modulo <code>10<sup>9</sup>+7</code>, and skip any jump target that falls outside the grid.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03

Algorithm Walkthrough

Iteration Checklist

  1. Define state (indices, window, stack, map, DP cell, or recursion frame).
  2. Apply one transition step and update the invariant.
  3. Record answer candidate when condition is met.
  4. Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04

Edge Cases

Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Upper-end input sizes
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05

Full Annotated Code

Source-backed implementations are provided below for direct study and interview prep.

// Accepted solution for LeetCode #3665: Twisted Mirror Path Count
// Auto-generated Java example from go.
class Solution {
    public void exampleSolution() {
    }
}
// Reference (go):
// // Accepted solution for LeetCode #3665: Twisted Mirror Path Count
// package main
// 
// // https://space.bilibili.com/206214
// func uniquePaths1(grid [][]int) (ans int) {
// 	const mod = 1_000_000_007
// 	m, n := len(grid), len(grid[0])
// 	memo := make([][][2]int, m)
// 	for i := range memo {
// 		memo[i] = make([][2]int, n)
// 		for j := range memo[i] {
// 			memo[i][j] = [2]int{-1, -1} // -1 表示没有计算过
// 		}
// 	}
// 	var dfs func(int, int, int) int
// 	dfs = func(i, j, k int) (res int) {
// 		if i < 0 || j < 0 {
// 			return 0
// 		}
// 		if i == 0 && j == 0 {
// 			return 1
// 		}
// 		p := &memo[i][j][k]
// 		if *p != -1 { // 之前计算过
// 			return *p
// 		}
// 		defer func() { *p = res }() // 记忆化
// 		if grid[i][j] == 0 {        // 没有镜子,随便走
// 			return (dfs(i, j-1, 0) + dfs(i-1, j, 1)) % mod
// 		}
// 		if k == 0 { // 从下边过来
// 			return dfs(i-1, j, 1) // 反射到左边
// 		}
// 		// 从右边过来
// 		return dfs(i, j-1, 0) // 反射到上边
// 	}
// 	return dfs(m-1, n-1, 0)
// }
// 
// func uniquePaths2(grid [][]int) (ans int) {
// 	const mod = 1_000_000_007
// 	m, n := len(grid), len(grid[0])
// 	f := make([][][2]int, m+1)
// 	for i := range f {
// 		f[i] = make([][2]int, n+1)
// 	}
// 	f[0][1] = [2]int{1, 1}
// 	for i, row := range grid {
// 		for j, x := range row {
// 			if x == 0 {
// 				f[i+1][j+1][0] = (f[i+1][j][0] + f[i][j+1][1]) % mod
// 				f[i+1][j+1][1] = f[i+1][j+1][0]
// 			} else {
// 				f[i+1][j+1][0] = f[i][j+1][1]
// 				f[i+1][j+1][1] = f[i+1][j][0]
// 			}
// 		}
// 	}
// 	return f[m][n][0]
// }
// 
// func uniquePaths(grid [][]int) (ans int) {
// 	const mod = 1_000_000_007
// 	n := len(grid[0])
// 	f := make([][2]int, n+1)
// 	f[1] = [2]int{1, 1}
// 	for _, row := range grid {
// 		for j, x := range row {
// 			if x == 0 {
// 				f[j+1][0] = (f[j][0] + f[j+1][1]) % mod
// 				f[j+1][1] = f[j+1][0]
// 			} else {
// 				f[j+1][0] = f[j+1][1]
// 				f[j+1][1] = f[j][0]
// 			}
// 		}
// 	}
// 	return f[n][0]
// }
Step 06

Interactive Study Demo

Use this to step through a reusable interview workflow for this problem.

Press Step or Run All to begin.
Step 07

Complexity Analysis

Time
O(n × m)
Space
O(n × m)

Approach Breakdown

RECURSIVE
O(2ⁿ) time
O(n) space

Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.

DYNAMIC PROGRAMMING
O(n × m) time
O(n × m) space

Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.

Shortcut: Count your DP state dimensions → that’s your time. Can you drop one? That’s your space optimization.
Coach Notes

Common Mistakes

Review these before coding to avoid predictable interview regressions.

Off-by-one on range boundaries

Wrong move: Loop endpoints miss first/last candidate.

Usually fails on: Fails on minimal arrays and exact-boundary answers.

Fix: Re-derive loops from inclusive/exclusive ranges before coding.

State misses one required dimension

Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.

Usually fails on: Correctness breaks on cases that differ only in hidden state.

Fix: Define state so each unique subproblem maps to one DP cell.