Problem 63

Abstract / Summary

A robot moves from the top left to the bottom right of a grid with obstacles find the number of unique paths.

Note

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

C++ 0063.cpp

class Solution {
public:
    int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
        if (obstacleGrid[0][0] == 1)
            return 0;

        int w = obstacleGrid.size();
        int h = obstacleGrid[0].size();

        vector<vector<int>> board;
        board.resize(w);
        for (auto& b : board)
            b.resize(h, 0);

        board[0][0] = 1;

        for (int x = 0; x < w; x++)
            for (int y = 0; y < h; y++)
            {
                if (obstacleGrid[x][y] == 1)
                    continue;

                if (x > 0 && obstacleGrid[x-1][y] == 0)
                    board[x][y] += board[x-1][y];
                if (y > 0 && obstacleGrid[x][y-1] == 0)
                    board[x][y] += board[x][y-1];
            }

        return board[w-1][h-1];
    }
};
31 lines | 843 bytes | submitted August 7, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 45% (3+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Dynamic Programming
  • 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 implementation solves the classic “unique paths with obstacles” problem using dynamic programming. It receives a two-dimensional integer grid where a cell value of 1 denotes an obstacle and 0 denotes a free space. The goal is to count how many distinct ways exist to travel from the top-left corner to the bottom-right corner while moving only down or right and never stepping on an obstacle. The algorithm builds a secondary matrix that records the number of ways to reach each cell, propagating counts while respecting obstacle locations.

Initialization and Early Exit

The first conditional checks whether the starting cell itself is blocked. If the top-left cell contains an obstacle, the function immediately returns 0, because no path can begin.

if (obstacleGrid[0][0] == 1)
    return 0;

After this guard, the dimensions of the input grid are stored in w (number of rows) and h (number of columns).

int w = obstacleGrid.size();
int h = obstacleGrid[0].size();

A secondary matrix named board is allocated with the same dimensions as the input. Each row is resized to h and initialized with zeros, ensuring that every cell starts with a count of zero.

vector<vector<int>> board;
board.resize(w);
for (auto& b : board)
    b.resize(h, 0);

The starting position in board is set to 1, representing a single way to be at the origin when it is not an obstacle.

board[0][0] = 1;

Main Dynamic Programming Loop

Two nested loops iterate over every cell in row-major order. The outer loop variable x traverses rows, while the inner loop variable y traverses columns.

for (int x = 0; x < w; x++)
    for (int y = 0; y < h; y++)
    {
        // body
    }

Inside the loop, the first test skips any cell that contains an obstacle, leaving its count unchanged (zero).

if (obstacleGrid[x][y] == 1)
    continue;

For free cells, the algorithm aggregates contributions from the cell directly above and the cell directly to the left, but only if those neighboring cells are also free. The condition x > 0 ensures that the algorithm does not read above the first row, and y > 0 protects against reading left of the first column.

if (x > 0 && obstacleGrid[x-1][y] == 0)
    board[x][y] += board[x-1][y];
if (y > 0 && obstacleGrid[x][y-1] == 0)
    board[x][y] += board[x][y-1];

By adding the counts from valid predecessors, board[x][y] ends up holding the total number of ways to reach that cell without crossing obstacles.

Result Extraction

After the loops have filled the entire board, the value at the bottom-right corner (board[w-1][h-1]) represents the total number of valid paths from start to finish. This value is returned as the final answer.

return board[w-1][h-1];

Edge Cases Handled

The code explicitly handles the situation where the entry cell is blocked, returning zero without further computation. It also gracefully processes grids where obstacles appear on the first row or first column; the boundary checks (x > 0 and y > 0) prevent out-of-range accesses while still allowing propagation of path counts when the neighboring cell is free. When the destination cell itself is an obstacle, the final entry in board remains zero because the inner loop never adds contributions to a blocked cell, resulting in a correct zero return.

Performance Optimizations

The algorithm avoids unnecessary work by allocating the auxiliary board matrix once and initializing it with zeros, which eliminates the need for repeated conditional resets during the DP pass. The early exit for a blocked start cell prevents the allocation and iteration steps entirely when no solution exists. By checking the obstacle status of predecessor cells before adding their counts, the code skips addition operations for blocked neighbors, reducing arithmetic overhead. The use of simple integer addition and direct indexing ensures that the inner loop runs with minimal instruction overhead, making the solution efficient for typical grid sizes.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a big grid laid out on the floor that looks like a tile floor, where some squares have blocks sitting on them that you cannot step over. You want to walk from the very top corner all the way to the bottom corner, but you are only allowed to move either to the right or down one square at a time. The goal is to find every possible path you could take to reach the end without bumping into any of those blocks.

To solve this, the code sets up a separate special board that tracks how many different ways there are to reach each specific square. It starts at the very beginning and marks that there is exactly one way to be at the start. Then, it looks at every other square on the floor in order. For each square, it checks if there is a block there. If there is, it just skips that spot because no path can go through it.

If there is no block, the code looks at the square directly behind it to the left and the square directly above it. It adds up all the ways to reach those two neighbors and writes that total inside the current square. By the time it finishes looking at every square row by row, the final spot at the end of the floor already has the total count of all the paths that reached it safely.

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 = 7 | μ = 6.70 | σ = 1.15

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 Python C++ Java TS
WalkCCC Python C++ Java
leetcode.ca Python C++ Java Rust JS Go TS
LeetcodeHelp Python C++ Java
MemoryLimitExceeded Python C++
Progiez Python C++ Java
github aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows Python
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
DimitrisJim C
everthis JS
FelixFan1122 C#
fengvyi C++
fpdjsns C++
gaosq0604 Python
Garvit244 Python
halfrost Go
haoel Java
JoshCrozier JS
keineahnung2345 C++
Krazune Java
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
qiyuangong Python
ruoru Rust
shreymehul C#
suxrobGM C#
trung-hn Python
varunu28 Java
XiaotaoGuo C++
YuriSpiridonov Python
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, JavaScript, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows Python, Python
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
DimitrisJim C
everthis JavaScript
FelixFan1122 C#
fengvyi C++
fpdjsns C++
gaosq0604 Python
Garvit244 Python
halfrost Go
haoel Java
JoshCrozier JavaScript
keineahnung2345 C++
Krazune Java
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
qiyuangong Python
ruoru Rust
shreymehul C#
suxrobGM C#
trung-hn Python
varunu28 Java
XiaotaoGuo C++
YuriSpiridonov Python
zfang399 C++
55 links | 39 authors | 9 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Unique Paths II - Leetcode 63 - Python'
NeetCodeIO 15 mins
Unique Paths II - Leetcode 63 - Python
YouTube video 'Unique Paths 2 | Dynamic Programming | Leetcode #63'
Techdose 17 mins
Unique Paths 2 | Dynamic Programming | Leetcode #63
YouTube video 'Unique Paths II | Recursion | Memo | Bottom Up | Leetcode 63 | DP On Grids | codestorywithMIK'
codestorywithMIK 46 mins
Unique Paths II | Recursion | Memo | Bottom Up | Leetcode 63 | DP On Grids | codestorywithMIK
YouTube video '[Java] Leetcode 63. Unique Paths II [DP Distinct Ways #3]'
Eric Programming 15 mins
[Java] Leetcode 63. Unique Paths II [DP Distinct Ways #3]
YouTube video 'LEETCODE 63 (JAVASCRIPT) | UNIQUE PATHS II | CODING INTERVIEW PREP'
Andy Gala 14 mins
LEETCODE 63 (JAVASCRIPT) | UNIQUE PATHS II | CODING INTERVIEW PREP
YouTube video 'Unique Paths II | Leetcode 63 | Dynamic Programming 🔥🔥🔥 | Easy Peasy | Live coding session'
Coding Decoded 10 mins
Unique Paths II | Leetcode 63 | Dynamic Programming 🔥🔥🔥 | Easy Peasy | Live coding session
YouTube video 'Unique Paths II | LeetCode 63 | Recursive Top Down Bottom Up DP | Facebook Amazon'
Naresh Gupta 13 mins
Unique Paths II | LeetCode 63 | Recursive Top Down Bottom Up DP | Facebook Amazon
YouTube video 'Daily Leetcode #780 part 2: May 20, 2022 - 63. Unique Paths II'
Programming Live with Larry 16 mins
Daily Leetcode #780 part 2: May 20, 2022 - 63. Unique Paths II
YouTube video '63. Unique Paths II - Leetcode Python Solution'
Code with Carter 8 mins
63. Unique Paths II - Leetcode Python Solution
YouTube video 'Leetcode 63 Unique Paths II (Java)'
TheAnalyticGuy 7 mins
Leetcode 63 Unique Paths II (Java)
YouTube video '63 || Unique Paths II || C++ || Leetcode Daily Challenge'
CodeFreaks 12 mins
63 || Unique Paths II || C++ || Leetcode Daily Challenge
YouTube video 'Daily Leetcode #1229: Aug 12, 2023 - 63. Unique Paths II'
Programming Live with Larry 10 mins
Daily Leetcode #1229: Aug 12, 2023 - 63. Unique Paths II
YouTube video 'Daily Leetcode #393: Apr 28, 2021 - 63. Unique Paths II'
Programming Live with Larry 16 mins
Daily Leetcode #393: Apr 28, 2021 - 63. Unique Paths II
YouTube video '63. Unique Paths II | Daily Leetcode Challenge | August | C++ | Java'
Mayur Programming Club 30 mins
63. Unique Paths II | Daily Leetcode Challenge | August | C++ | Java
YouTube video 'Unique Paths II - LeetCode 63 - Python - Memoization - Bottom Up Dp'
Alpha-Code 25 mins
Unique Paths II - LeetCode 63 - Python - Memoization - Bottom Up Dp
YouTube video '63. Unique Paths II - DP - LeetCode Daily Challenge - JavaScript'
LeetCodeWithMonu 21 mins
63. Unique Paths II - DP - LeetCode Daily Challenge - JavaScript
YouTube video 'Unique Paths II | Leetcode 63 | Coders Camp'
Coders Camp 17 mins
Unique Paths II | Leetcode 63 | Coders Camp
YouTube video 'DP 6. Introduction to Grid DP | Unique Paths II | Leetcode 62 and 63 | Interview Problems'
Eye on AI and DSA 26 mins
DP 6. Introduction to Grid DP | Unique Paths II | Leetcode 62 and 63 | Interview Problems
YouTube video 'Leetcode solving 63  Unique Paths II'
Math Geeks 4 mins
Leetcode solving 63 Unique Paths II
YouTube video 'Can you find it? (LeetCode: Unique Paths II)'
Code With Zi 15 mins
Can you find it? (LeetCode: Unique Paths II)
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

4 similar problems

Solved On The Same Day

40 easy 30 medium 1 hard
72 solutions   August 7, 2023

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