graph search Pattern
71 problems
Pattern pages help build reusable solving frames. Identify signals first, then explain state, transition, and edge handling.
Recognition Signals
- Do you understand how BFS guarantees the shortest path in a word transformation sequence?
- Can you explain why a hash table improves the performance of this problem?
- Do you understand how Depth-First Search can be applied to matrix traversal?
Solve Flow
- 1. Define the active state/window.
- 2. Update state while preserving invariants.
- 3. Validate with edge-heavy examples.
Common Misses
- Not checking if `endWord` is in the `wordList` before starting the BFS, leading to unnecessary computation.
- Failing to properly mark border 'O's as safe, leading to incorrect regions being transformed.
- Failing to mark visited cells, causing infinite loops or double-counting.
Recommended Ladder
Word Ladder
Find the shortest transformation sequence from a start word to an end word, with each word in the sequence differing by …
Surrounded Regions
Transform the matrix in-place by marking regions surrounded by 'X' as 'X', while keeping border-adjacent 'O's intact.
Number of Islands
Count the number of distinct islands in a binary grid using array traversal combined with depth-first search exploration…
Course Schedule
Determine if all courses can be completed by analyzing prerequisite dependencies using indegree tracking and topological…
Course Schedule II
Solve the 'Course Schedule II' problem using graph indegree and topological ordering, utilizing DFS or BFS to find the c…
Design Add and Search Words Data Structure
Build a WordDictionary supporting dynamic word addition and search with wildcard matching efficiently using Trie and DFS…
Minimum Height Trees
Identify all roots of a tree that produce minimum height using graph indegree analysis and topological trimming.
Water and Jug Problem
Determine if two jugs with given capacities can measure an exact target amount using math and DFS strategies efficiently…
Lexicographical Numbers
Generate all numbers from 1 to n in lexicographical order using a depth-first search pattern optimized with trie logic f…
Trapping Rain Water II
Solve Trapping Rain Water II using breadth-first search and priority queues for efficient water trapping in a matrix.
Pacific Atlantic Water Flow
Find all cells on an island where water can flow to both the Pacific and Atlantic oceans using DFS or BFS.
Battleships in a Board
Count the number of non-overlapping battleships on a 2D board using array traversal and depth-first search patterns effi…
Minimum Genetic Mutation
Determine the minimum number of single-character gene mutations to reach the target gene using BFS and a hash table look…
Island Perimeter
Determine the perimeter of an island in a grid of land and water cells using DFS or BFS.
Minesweeper
Solve the Minesweeper game by updating revealed squares and handling clicks with Depth-First Search and Array manipulati…
Array Nesting
Find the longest nested set in a permutation array using a depth-first traversal, handling cycles efficiently for medium…
Cut Off Trees for Golf Event
Determine the minimum steps to cut all trees in a forest matrix in ascending height order using BFS traversal and priori…
Implement Magic Dictionary
Design a Magic Dictionary to allow searching with one-character modifications, using Hash Table and String techniques.
Max Area of Island
Find the largest connected land area in a binary grid using array traversal and depth-first search efficiently.
Flood Fill
Flood Fill is an array and DFS problem where you change connected pixels to a target color efficiently using recursion o…
Contain Virus
Contain Virus involves using array-based Depth-First Search to contain viral spread by building walls around infected re…
Pyramid Transition Matrix
The Pyramid Transition Matrix problem requires determining whether a pyramid can be formed with given blocks and valid p…
Find Eventual Safe States
Solve the problem of finding eventual safe states in a directed graph using depth-first search and topological sorting.
Making A Large Island
Calculate the largest island size by converting at most one zero in a binary grid using array and DFS techniques efficie…
Loud and Rich
Determine the quietest person richer than each individual using graph indegree analysis and topological ordering techniq…
K-Similar Strings
K-Similar Strings involves finding the minimal number of swaps to transform one string into another through character sw…
Shortest Path to Get All Keys
Find the minimum steps to collect all keys in a grid using BFS and bitmasking, handling locks efficiently.
Snakes and Ladders
Solve the Snakes and Ladders problem using a BFS strategy to efficiently navigate the board and reach the final square.
Shortest Bridge
Find the minimum flips to connect two separate islands in a binary matrix using Array and DFS techniques efficiently.
Rotting Oranges
Given a grid with fresh and rotten oranges, return the minimum time for all oranges to rot or -1 if impossible.
Number of Enclaves
This problem involves finding the number of land cells that cannot reach the boundary in a grid using DFS and array mani…
Coloring A Border
Given a grid and a starting cell, color all border cells of the connected component using DFS while preserving interior …
Shortest Path in Binary Matrix
Find the shortest clear path in a binary matrix using BFS, carefully handling obstacles and diagonal movements for effic…
Shortest Path with Alternating Colors
Solve the shortest path problem with alternating edge colors using graph traversal and BFS.
Sort Items by Groups Respecting Dependencies
Sort items into groups while respecting dependencies using graph indegree tracking and topological ordering patterns eff…
Minimum Moves to Reach Target with Rotations
Find the minimum moves for a 2-cell snake to reach the bottom-right corner using rotations and BFS traversal in a grid.
Number of Closed Islands
Count the number of closed islands in a 2D grid using array traversal and depth-first search efficiently.
Minimum Moves to Move a Box to Their Target Location
Solve the minimum moves to push a box to its target using BFS and priority handling in a grid-based warehouse layout eff…
Count Servers that Communicate
Count Servers that Communicate involves identifying servers in a grid that can communicate based on row or column connec…
Shortest Path in a Grid with Obstacles Elimination
Find the shortest path in a grid with obstacles, allowing the elimination of up to k obstacles using BFS.
Maximum Candies You Can Get from Boxes
Collect maximum candies from boxes by exploring initially available boxes and using keys to unlock additional ones effic…
Jump Game III
Jump Game III challenges you to determine if you can reach any zero in an array using jumps defined by array values, tes…
Minimum Cost to Make at Least One Valid Path in a Grid
Determine the minimum cost to create at least one valid path from the top-left to bottom-right in a directional grid.
Check if There is a Valid Path in a Grid
Check if there is a valid path from the upper-left to the bottom-right corner of a grid using depth-first search.
Course Schedule IV
Determine if one course is a prerequisite of another using graph indegree tracking and topological ordering efficiently.
Detect Cycles in 2D Grid
Detect cycles in a 2D character grid using DFS while carefully tracking parent cells to avoid invalid revisits.
Minimum Number of Days to Disconnect Island
Find the minimum number of days to disconnect an island in a grid using depth-first search.
Lexicographically Smallest String After Applying Operations
Optimize a string through rotations and additions to get the lexicographically smallest possible result using string man…
Minimize Hamming Distance After Swap Operations
Solve Minimize Hamming Distance After Swap Operations by grouping swappable indices and matching value counts inside eac…
Map of Highest Peak
Solve the Map of Highest Peak problem using breadth-first search to assign heights based on proximity to water cells.
Count Sub Islands
Identify and count all islands in grid2 that are fully contained within islands of grid1 using DFS traversal efficiently…
Nearest Exit from Entrance in Maze
Find the shortest path from the maze entrance to the nearest border exit using BFS over a 2D array matrix efficiently.
Find All Groups of Farmland
Identify all rectangular farmland groups in a binary matrix using array traversal and depth-first search efficiently.
The Time When the Network Becomes Idle
Calculate the time when the network becomes idle, factoring in message resending and the BFS traversal method.
Second Minimum Time to Reach Destination
Find the second minimum time to reach a destination using BFS while accounting for traffic signal delays in a graph trav…
Minimum Operations to Convert Number
Determine the minimum operations needed to convert a number using array elements with addition, subtraction, or XOR oper…
Maximum Employees to Be Invited to a Meeting
Determine the maximum employees to invite based on favorite adjacency constraints using graph indegree and topological o…
K Highest Ranked Items Within a Price Range
Use BFS to rank reachable shop items by distance, price, row, and column, then return the best k coordinates.
All Ancestors of a Node in a Directed Acyclic Graph
Solve the All Ancestors of a Node in a Directed Acyclic Graph problem using graph traversal techniques like BFS, DFS, an…
Longest Path With Different Adjacent Characters
Find the longest path in a tree where adjacent nodes have different characters using graph DFS and topological reasoning…
Minimum Obstacle Removal to Reach Corner
Find the minimum obstacles to remove in a 2D grid to reach the bottom-right corner using BFS graph traversal techniques.
Longest Cycle in a Graph
The problem asks to find the longest cycle in a directed graph with specific edge constraints.
Minimum Time to Visit a Cell In a Grid
Compute the fastest path in a grid where each cell has a minimum time requirement using BFS and priority queue technique…
Check Knight Tour Configuration
Validate a knight's movement configuration on an n x n chessboard to check if it forms a valid Knight's Tour.
Shortest Cycle in a Graph
Find the shortest cycle in a bi-directional graph using BFS for optimal traversal.
Minimum Reverse Operations
Find the minimum number of operations to move a 1 in an array from a given start position to other positions, considerin…
Maximum Number of Fish in a Grid
Maximize the number of fish that can be caught by performing DFS on an optimal starting point in a grid.
Count the Number of Houses at a Certain Distance I
Determine the number of house pairs at each street distance using graph traversal and breadth-first search efficiently.
Shortest Distance After Road Addition Queries I
Solve shortest paths dynamically in a growing graph using BFS, updating distances efficiently after each road addition q…
Find a Safe Walk Through a Grid
Determine if you can safely traverse a binary grid from top-left to bottom-right using limited health points.
Count Islands With Total Value Divisible by K
Count the number of islands in a grid where the sum of each island's values is divisible by a given integer k.