LeetCodechevron_rightgraph search

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. 1. Define the active state/window.
  2. 2. Update state while preserving invariants.
  3. 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

#TitleDifficulty
127

Word Ladder

Find the shortest transformation sequence from a start word to an end word, with each word in the sequence differing by …

Hard
130

Surrounded Regions

Transform the matrix in-place by marking regions surrounded by 'X' as 'X', while keeping border-adjacent 'O's intact.

Medium
200

Number of Islands

Count the number of distinct islands in a binary grid using array traversal combined with depth-first search exploration…

Medium
207

Course Schedule

Determine if all courses can be completed by analyzing prerequisite dependencies using indegree tracking and topological…

Medium
210

Course Schedule II

Solve the 'Course Schedule II' problem using graph indegree and topological ordering, utilizing DFS or BFS to find the c…

Medium
211

Design Add and Search Words Data Structure

Build a WordDictionary supporting dynamic word addition and search with wildcard matching efficiently using Trie and DFS…

Medium
310

Minimum Height Trees

Identify all roots of a tree that produce minimum height using graph indegree analysis and topological trimming.

Medium
365

Water and Jug Problem

Determine if two jugs with given capacities can measure an exact target amount using math and DFS strategies efficiently…

Medium
386

Lexicographical Numbers

Generate all numbers from 1 to n in lexicographical order using a depth-first search pattern optimized with trie logic f…

Medium
407

Trapping Rain Water II

Solve Trapping Rain Water II using breadth-first search and priority queues for efficient water trapping in a matrix.

Hard
417

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.

Medium
419

Battleships in a Board

Count the number of non-overlapping battleships on a 2D board using array traversal and depth-first search patterns effi…

Medium
433

Minimum Genetic Mutation

Determine the minimum number of single-character gene mutations to reach the target gene using BFS and a hash table look…

Medium
463

Island Perimeter

Determine the perimeter of an island in a grid of land and water cells using DFS or BFS.

Easy
529

Minesweeper

Solve the Minesweeper game by updating revealed squares and handling clicks with Depth-First Search and Array manipulati…

Medium
565

Array Nesting

Find the longest nested set in a permutation array using a depth-first traversal, handling cycles efficiently for medium…

Medium
675

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…

Hard
676

Implement Magic Dictionary

Design a Magic Dictionary to allow searching with one-character modifications, using Hash Table and String techniques.

Medium
695

Max Area of Island

Find the largest connected land area in a binary grid using array traversal and depth-first search efficiently.

Medium
733

Flood Fill

Flood Fill is an array and DFS problem where you change connected pixels to a target color efficiently using recursion o…

Easy
749

Contain Virus

Contain Virus involves using array-based Depth-First Search to contain viral spread by building walls around infected re…

Hard
756

Pyramid Transition Matrix

The Pyramid Transition Matrix problem requires determining whether a pyramid can be formed with given blocks and valid p…

Medium
802

Find Eventual Safe States

Solve the problem of finding eventual safe states in a directed graph using depth-first search and topological sorting.

Medium
827

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…

Hard
851

Loud and Rich

Determine the quietest person richer than each individual using graph indegree analysis and topological ordering techniq…

Medium
854

K-Similar Strings

K-Similar Strings involves finding the minimal number of swaps to transform one string into another through character sw…

Hard
864

Shortest Path to Get All Keys

Find the minimum steps to collect all keys in a grid using BFS and bitmasking, handling locks efficiently.

Hard
909

Snakes and Ladders

Solve the Snakes and Ladders problem using a BFS strategy to efficiently navigate the board and reach the final square.

Medium
934

Shortest Bridge

Find the minimum flips to connect two separate islands in a binary matrix using Array and DFS techniques efficiently.

Medium
994

Rotting Oranges

Given a grid with fresh and rotten oranges, return the minimum time for all oranges to rot or -1 if impossible.

Medium
1020

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…

Medium
1034

Coloring A Border

Given a grid and a starting cell, color all border cells of the connected component using DFS while preserving interior …

Medium
1091

Shortest Path in Binary Matrix

Find the shortest clear path in a binary matrix using BFS, carefully handling obstacles and diagonal movements for effic…

Medium
1129

Shortest Path with Alternating Colors

Solve the shortest path problem with alternating edge colors using graph traversal and BFS.

Medium
1203

Sort Items by Groups Respecting Dependencies

Sort items into groups while respecting dependencies using graph indegree tracking and topological ordering patterns eff…

Hard
1210

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.

Hard
1254

Number of Closed Islands

Count the number of closed islands in a 2D grid using array traversal and depth-first search efficiently.

Medium
1263

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…

Hard
1267

Count Servers that Communicate

Count Servers that Communicate involves identifying servers in a grid that can communicate based on row or column connec…

Medium
1293

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.

Hard
1298

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…

Hard
1306

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…

Medium
1368

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.

Hard
1391

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.

Medium
1462

Course Schedule IV

Determine if one course is a prerequisite of another using graph indegree tracking and topological ordering efficiently.

Medium
1559

Detect Cycles in 2D Grid

Detect cycles in a 2D character grid using DFS while carefully tracking parent cells to avoid invalid revisits.

Medium
1568

Minimum Number of Days to Disconnect Island

Find the minimum number of days to disconnect an island in a grid using depth-first search.

Hard
1625

Lexicographically Smallest String After Applying Operations

Optimize a string through rotations and additions to get the lexicographically smallest possible result using string man…

Medium
1722

Minimize Hamming Distance After Swap Operations

Solve Minimize Hamming Distance After Swap Operations by grouping swappable indices and matching value counts inside eac…

Medium
1765

Map of Highest Peak

Solve the Map of Highest Peak problem using breadth-first search to assign heights based on proximity to water cells.

Medium
1905

Count Sub Islands

Identify and count all islands in grid2 that are fully contained within islands of grid1 using DFS traversal efficiently…

Medium
1926

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.

Medium
1992

Find All Groups of Farmland

Identify all rectangular farmland groups in a binary matrix using array traversal and depth-first search efficiently.

Medium
2039

The Time When the Network Becomes Idle

Calculate the time when the network becomes idle, factoring in message resending and the BFS traversal method.

Medium
2045

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…

Hard
2059

Minimum Operations to Convert Number

Determine the minimum operations needed to convert a number using array elements with addition, subtraction, or XOR oper…

Medium
2127

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…

Hard
2146

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.

Medium
2192

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…

Medium
2246

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…

Hard
2290

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.

Hard
2360

Longest Cycle in a Graph

The problem asks to find the longest cycle in a directed graph with specific edge constraints.

Hard
2577

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…

Hard
2596

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.

Medium
2608

Shortest Cycle in a Graph

Find the shortest cycle in a bi-directional graph using BFS for optimal traversal.

Hard
2612

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…

Hard
2658

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.

Medium
3015

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.

Medium
3243

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…

Medium
3286

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.

Medium
3619

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.

Medium

Related Topics

Hash Table plus String LeetCode Pattern: 71 Solutions