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];
}
};
Difficulty
and has an acceptance rate of about 45% (3+ million submissions).
Typical patterns to solve this problem:
- Array
- Dynamic Programming
- Matrix
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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++ |
Videos
Similar Problems
- problem 62: Unique Paths
- problem 980: Unique Paths III
- problem 2304: Minimum Path Cost in a Grid
- problem 2435: Paths in Matrix Whose Sum Is Divisible by K
Solved On The Same Day
- problem 13: Roman to Integer
- problem 21: Merge Two Sorted Lists
- problem 28: Find the Index of the First Occurrence in a String
- problem 35: Search Insert Position
- problem 58: Length of Last Word
- problem 66: Plus One
- problem 67: Add Binary
- problem 69: Sqrt(x)
- problem 70: Climbing Stairs
- problem 206: Reverse Linked List
- problem 242: Valid Anagram
- problem 278: First Bad Version
- problem 283: Move Zeroes
- problem 367: Valid Perfect Square
- problem 374: Guess Number Higher or Lower
- problem 389: Find the Difference
- problem 441: Arranging Coins
- problem 459: Repeated Substring Pattern
- problem 509: Fibonacci Number
- problem 657: Robot Return to Origin
- problem 682: Baseball Game
- problem 704: Binary Search
- problem 709: To Lower Case
- problem 744: Find Smallest Letter Greater Than Target
- problem 746: Min Cost Climbing Stairs
- problem 860: Lemonade Change
- problem 896: Monotonic Array
- problem 976: Largest Perimeter Triangle
- problem 1137: N-th Tribonacci Number
- problem 1232: Check If It Is a Straight Line
- problem 1275: Find Winner on a Tic Tac Toe Game
- problem 1351: Count Negative Numbers in a Sorted Matrix
- problem 1491: Average Salary Excluding the Minimum and Maximum Salary
- problem 1502: Can Make Arithmetic Progression From Sequence
- problem 1523: Count Odd Numbers in an Interval Range
- problem 1539: Kth Missing Positive Number
- problem 1572: Matrix Diagonal Sum
- problem 1672: Richest Customer Wealth
- problem 1768: Merge Strings Alternately
- problem 1822: Sign of the Product of an Array
- problem 2: Add Two Numbers
- problem 5: Longest Palindromic Substring
- problem 33: Search in Rotated Sorted Array
- problem 34: Find First and Last Position of Element in Sorted Array
- problem 43: Multiply Strings
- problem 50: Pow(x, n)
- problem 54: Spiral Matrix
- problem 62: Unique Paths
- problem 64: Minimum Path Sum
- problem 73: Set Matrix Zeroes
- problem 74: Search a 2D Matrix
- problem 120: Triangle
- problem 139: Word Break
- problem 153: Find Minimum in Rotated Sorted Array
- problem 198: House Robber
- problem 221: Maximal Square
- problem 275: H-Index II
- problem 279: Perfect Squares
- problem 300: Longest Increasing Subsequence
- problem 436: Find Right Interval
- problem 445: Add Two Numbers II
- problem 528: Random Pick with Weight
- problem 540: Single Element in a Sorted Array
- problem 611: Valid Triangle Number
- problem 658: Find K Closest Elements
- problem 852: Peak Index in a Mountain Array
- problem 981: Time Based Key-Value Store
- problem 1041: Robot Bounded In Circle
- problem 1146: Snapshot Array
- problem 2300: Successful Pairs of Spells and Potions
- problem 154: Find Minimum in Rotated Sorted Array II
Extra
- 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