Curated sets

Graphs and traversal

BFS, DFS, shortest paths, and trees.

All problems
Total results3,710 problems
TopicsJudge
Is the Kid in Green Zelda?Find the minimum total cost path from the top-left to the bottom-right cell of an N x N grid where each cell's value is paid when visited.Medium4GraphShortest path+2No attempts yet1s256 MBJudgeable
Relative RelativesGiven Ted's age of 100 and each descendant's father name plus the father's age at the child's birth, compute every descendant's age and list them oldest first, ties broken by name.Medium4TreeDFS+2No attempts yet1s128 MBJudgeable
Here We Go(relians) AgainFind the shortest travel time across a grid of streets with posted integer speeds, one-way rules, and closed roads.Medium4GraphShortest path+2No attempts yet1s128 MBJudgeable
Pascal's TravelsCount paths on an n by n digit board from top-left to bottom-right, where each square's digit sets the exact right or down step length.Medium4Dynamic programmingArray+2No attempts yet1s128 MBJudgeable
Jungle RoadsGiven a connected weighted graph of villages and roads, find the minimum total maintenance cost of a set of roads that keeps every village connected.Medium4Minimum spanning treeGraph+2No attempts yet1s128 MBJudgeable
Image PerimetersGiven a grid and a click, find all X squares connected to the click by 8-direction adjacency and report the perimeter of that object.Medium4BFSDFS+2No attempts yet1s128 MBJudgeable
Robot MotionSimulate a robot walking a grid of N/S/E/W arrows from a given top column, and report either the steps to exit or the steps before a loop plus its length.Medium4SimulationGraph+1No attempts yet1s128 MBJudgeable
Oil DepositsCount connected components of oil pockets (@) in a grid where cells connect in all eight directions; input ends when m is 0.Medium4GraphDFS+2No attempts yet1s128 MBJudgeable
Underground CablesGiven up to 1000 points, connect them all with straight line segments of minimum total length, with no two segments crossing.Medium4Minimum spanning treeGraph+2No attempts yet1s128 MBJudgeable
Robot NavigationFind the length of the shortest command program that walks a robot from start to destination with turns and moves, and count distinct shortest programs modulo m.Medium4BFSGraph+1No attempts yet1s128 MBJudgeable
Tree GraftingGiven a depth-first traversal string of an ordered tree, report its height and the height after converting it to a left-child/right-sibling binary tree.Medium4TreeStack+2No attempts yet1s128 MBJudgeable
Winter FestivalGiven each person's single gift recipient, print every giving cycle in the order their first names appear in the input.Medium4GraphDFS+1No attempts yet1s128 MBJudgeable
Spreadsheet Circular ReferenceGiven spreadsheet cell formulas as lines, decide for each defined cell whether evaluating it leads to a circular reference, printing the cell name and circular or ok.Medium4GraphDFS+1No attempts yet1s128 MBJudgeable
Triangle GraphFind the minimum vertex-cost path from top-center to bottom-center in a layered 3-column DAG over N rows.Medium4Dynamic programmingGraphNo attempts yet1s256 MBJudgeable
Stock ChaseGiven share-purchase transactions between companies in order, count how many must be rejected because they would create a cycle.Medium4Union-findGraphNo attempts yet1s128 MBJudgeable
Amazing MazesGiven a rectangular grid with walls between cells, find the number of cells on the shortest path from the top-left opening to the bottom-right opening, or 0 if none exists.Medium4BFSGraph+2No attempts yet1s128 MBJudgeable
ElevatorAn elevator with buttons that move up U or down D floors, staying within floors 1 to F, needs the minimum presses to go from floor S to floor G.Medium4BFSGraph+2No attempts yet1s256 MBJudgeable
Money MattersGiven each person's balance and a friendship graph, decide whether all debts can be settled by moving money only within connected components.Medium4Union-findGraph+1No attempts yet1s128 MBJudgeable
Oily CurrentsSimulate oil spreading on a grid for t steps, where each contaminated cell pushes oil up to its strength in its current's direction. Print the final contaminated cells.Medium4SimulationBFS+2No attempts yet1s128 MBJudgeable
Emergency ResponseGiven a directed weighted graph, answer multiple queries: the shortest travel time from any of several start nodes to one crime intersection.Medium4GraphShortest path+2No attempts yet1s128 MBJudgeable
Prefix CodesDecode several binary messages with a prefix code given as a heap-indexed tree string, where a bit 0 or 1 walks to a child until a leaf symbol is reached.Medium4TreeImplementation+2No attempts yet1s128 MBJudgeable
HexGiven a Hex board of size n, decide whether Black, White, or nobody has a connecting path between the required edges.Medium4GraphDFS+1No attempts yet1s128 MBJudgeable
Quick out of the HarbourFind the shortest time from S to outside the grid, where water cells cost 1 and drawbridges cost 1+d, on a grid up to 500x500.Medium4GraphShortest path+2No attempts yet1s128 MBJudgeable
CheeseIn a grid maze, find the total shortest walking time for a mouse to eat cheeses of hardness 1 through N in order, each raising its strength by one.Medium4BFSGraph+2No attempts yet1s256 MBJudgeable
WeddingGiven a friendship graph among n classmates, count everyone within distance 2 of classmate 1.Medium4GraphBFS+2No attempts yet1s128 MBJudgeable
Army BuddiesAfter each loss report removes living soldiers L through R, print the nearest surviving neighbors on both sides, or * when none exists.Medium4Union-findLinked list+1No attempts yet1s128 MBJudgeable
Message RelayEach cow forwards to at most one other cow; count cows whose messages never reach a cycle and instead stop.Medium4GraphDFS+1No attempts yet1s128 MBJudgeable
PerimeterGiven up to 10000 occupied cells in a 100 by 100 grid forming one connected region, find the outer perimeter, ignoring any holes.Medium4BFSGraph+2No attempts yet1s128 MBJudgeable
Space ExplorationCount the connected components of asterisk cells in an N x N grid, where cells connect only along shared edges, not corners.Medium4GraphDFS+2No attempts yet1s128 MBJudgeable
Meeting PlaceGiven a rooted tree and M queries, report the lowest common ancestor of two nodes for each query.Medium4TreeDFS+2No attempts yet1s128 MBJudgeable
PathfindingGiven a directed graph as an adjacency matrix and a start node, print the nodes first reached at each successive distance using BFS.Medium4GraphBFSNo attempts yet1s128 MBJudgeable
Heat WaveGiven an undirected weighted graph, find the minimum total cost of a route from a source town to a destination town.Medium4GraphShortest path+2No attempts yet1s128 MBJudgeable
The Chivalrous CowFind the fewest knight-move jumps on an X by Y grid with obstacles to get from the start square to the hay bale.Medium4BFSGraph+2No attempts yet1s128 MBJudgeable
Guarding the FarmCount connected groups of equal-altitude cells, using 8-direction adjacency, that are surrounded only by lower altitude or the map edge.Medium4GraphDFS+2No attempts yet1s128 MBJudgeable
Hide and SeekIn a connected undirected graph, find the barn farthest from barn 1. Print the smallest such barn number, its distance, and how many barns tie at that distance.Medium4GraphBFS+2No attempts yet1s256 MBJudgeable
Going to Meet SinaGiven up to 10^4 blocked cells on a bounded grid, find the shortest 4-directional path from (0,0) to (X,Y) avoiding all puddles.Medium4BFSGraph+2No attempts yet1s128 MBJudgeable
Oh Those RollersRollers touch when the distance between centers equals the sum of radii. Starting from the roller at the origin, follow the chain to the roller that drives no other and print its coordinates.Medium4GraphDFS+2No attempts yet1s128 MBJudgeable
Clear and Present DangerGiven a danger matrix and a required sequence of islands, find the minimum total danger of a walk that visits those islands in order, allowing detours through others.Medium4GraphShortest path+2No attempts yet1s128 MBJudgeable
Clear Cold WaterGiven a rooted binary tree described by branch points, print the distance from the barn to the endpoint of every pipe.Medium4TreeBFS+2No attempts yet1s128 MBJudgeable
Cow PicnicGiven K starting pastures and a directed graph, count the pastures reachable from every one of the K starting positions.Medium4GraphDFS+2No attempts yet1s128 MBJudgeable
Bronze Lilypad PondFind the minimum number of generalized knight's moves to get from the start lilypad to the destination on a grid, where only landing cells must be lilypads.Medium4BFSGraph+1No attempts yet1s128 MBJudgeable
Bronze Cow PartyGiven a connected undirected weighted graph, find twice the largest shortest-path distance from a fixed farm X, which is the longest round trip any cow makes.Medium4Shortest pathGraph+2No attempts yet1s128 MBJudgeable
The die is castGiven a grid picture of dice drawn with background, die, and dot pixels, count the connected dot regions inside each connected die region and print the counts sorted.Medium4DFSBFS+2No attempts yet1s128 MBJudgeable
N-Credible MazesGiven a dimension n and a list of paths between adjacent lattice points, decide if start and end coordinates are connected.Medium4GraphDFS+2No attempts yet1s128 MBJudgeable
Theseus and the MinotaurSimulate a chase through a directed cavern maze where Theseus drops candles every k-th cavern and the Minotaur always takes its first exit not leading to a candle.Medium4SimulationGraph+1No attempts yet1s128 MBJudgeable
Mapping the RouteSimulate a west, north, east, south backtracking search on a small walled grid, number the route cells, mark other visited cells with ???, and draw the maze.Medium4DFSBacktracking+2No attempts yet1s128 MBJudgeable
Is It a Tree?For each test case, read directed edges until a pair of zeros and decide whether the graph is a tree under the three given conditions, printing the case number and verdict.Medium4GraphUnion-find+2No attempts yet1s128 MBJudgeable
RiskGiven a 20-country border graph, answer queries for the fewest countries to conquer when moving from one country to another, counting the destination.Medium4GraphBFS+2No attempts yet1s128 MBJudgeable
The Sangbeom BuildingGiven a 3D grid of blocked and open cells with a start and an exit, find the minimum number of moves (or report impossible).Medium4BFSGraph+2No attempts yet1s128 MBJudgeable
Tree RecoveryGiven a binary tree's preorder and inorder traversal strings, print its postorder traversal. Process runs until end of file.Medium4TreeRecursion+1No attempts yet1s128 MBJudgeable
Knight MovesFor each pair of squares, find the minimum number of knight moves between them on a standard 8 by 8 chessboard.Medium4BFSGraph+1No attempts yet1s128 MBJudgeable
Gregory the GrasshopperFind the fewest knight moves from one square to another on a grid of up to 100 by 100, or report that it is impossible.Medium4BFSGraph+1No attempts yet1s128 MBJudgeable
Who is taller?Given comparisons stating x is taller than y, decide whether p is taller than q, q is taller than p, or neither is known.Medium4GraphDFS+1No attempts yet1s128 MBJudgeable
Knight HopOn an 8 by 8 board, find the fewest knight moves from a start square to a target square.Medium4BFSGraph+2No attempts yet2s512 MBJudgeable
From Prefix to PostfixTranslate each prefix arithmetic expression over + and - into its equivalent postfix form, stopping at the terminating 0.Medium4StackTree+2No attempts yet1s128 MBJudgeable
MazeFind the shortest path in a grid where each cell dictates which directions you may exit, counting cells visited.Medium4BFSGraph+1No attempts yet1s128 MBJudgeable
WaterparkCount the number of distinct paths from point 1 to point n in a DAG where every edge goes from a lower to a higher numbered point.Medium4Dynamic programmingGraphNo attempts yet1s128 MBJudgeable
It’s tough being a teen!Given a fixed list of seven tasks with precedence rules plus up to ten extra constraints, output a valid order using the smallest available task first, or report that no order exists.Medium4GraphTopological sort+2No attempts yet1s128 MBJudgeable
Floor PlanGiven a grid of walls and floor cells, count connected rooms, sort them by size, floor as many of the largest rooms as the wood supply allows, and report how many rooms got flooring plus the leftover wood.Medium4DFSSorting+2No attempts yet1s128 MBJudgeable
The Monkey DanceEach monkey follows one outgoing arrow per step on a permutation; find the step count when all monkeys are back home, which is the LCM of the cycle lengths.Medium4GraphMath+2No attempts yet1s128 MBJudgeable
Packet RoutingGiven a tree with weighted edges connecting N computers, compute the travel time along the unique path between each query pair of computers.Medium4TreeDFS+2No attempts yet1s128 MBJudgeable
Bad CowtractorsGiven an undirected weighted graph, find a spanning tree of maximum total edge cost, or report -1 if no spanning tree exists.Medium4Minimum spanning treeGreedy+2No attempts yet1s128 MBJudgeable
Christmas Tree OrnamentA tree of N lamps is built incrementally and recolored M times; after each recolor, report how many edges join two lamps of equal color.Medium4TreeImplementationNo attempts yet1s1024 MBJudgeable
BossesGiven a graph of projects where the lower-numbered endpoint is the boss, find the max number of edges so every vertex has at most one boss, minimizing cancellations.Medium4GraphGreedy+2No attempts yet1s1024 MBJudgeable
Disk TreeGiven full directory paths, rebuild the tree and print every directory name on its own line, indented by depth, with siblings in ASCII order.Medium4TrieSorting+1No attempts yet1s128 MBJudgeable
The Mysterious X NetworkGiven an undirected graph of N people, find the minimum number of intermediate people on a shortest path between two given people.Medium4GraphBFS+2No attempts yet1s128 MBJudgeable
Mine MapMark each cell of a grid as mine, safely entered, risky, or unreachable, following a detector-driven walk from the center.Medium4BFSSimulation+1No attempts yet1s128 MBJudgeable
Holiday GiftsAssign one of two priced gifts to each node of a rooted tree so no two adjacent employees share a gift, minimizing total cost.Medium4TreeDynamic programming+2No attempts yet1s128 MBJudgeable
Scavenger HuntGiven S-1 ordered pairs of steps from a route of S steps, reconstruct the full sequence of steps in order.Medium4GraphHash map+1No attempts yet1s128 MBJudgeable
Manhattan 2025Given at most 9 units of fuel, print the smallest cube of grid intersections reachable from the origin, digit by digit, slice by slice.Medium4BFSMatrix+1No attempts yet1s128 MBJudgeable
Knight's MoveGiven an l by l board and two squares, find the minimum number of knight moves between them.Medium4BFSGraph+1No attempts yet1s256 MBJudgeable
TomatoesGiven a grid of ripe, unripe, and empty cells, find how many days until every tomato ripens or report -1 if some never can.Medium4BFSGraph+2No attempts yet1s256 MBJudgeable
SSSP (Shortest Path Queries)Run the given SPFA shortest-path algorithm for each query and also output a push counter that accumulates across all queries.Medium4Shortest pathGraph+2No attempts yet1s128 MBJudgeable
Handong the Salesman!Given a tree, start at node 1 and visit m listed nodes in order, summing the tree distances between consecutive stops.Medium4GraphTree+2No attempts yet1s128 MBJudgeable
PolygonGiven a convex polygon and a set of non-crossing diagonals, report the largest number of sides among the pieces the diagonals divide it into.Medium4GraphDFS+2No attempts yet1s128 MBJudgeable
DyzioParse a 0/1 description of recursive halving cuts and output the cut count at which the first shortest piece appears.Medium4TreeDFS+2No attempts yet1s128 MBJudgeable
Odd-Length CycleFor each of t undirected graphs, decide whether it contains an odd-length cycle (equivalently, is not bipartite).Medium4GraphBFS+1No attempts yet1s128 MBJudgeable
MegavirusGiven k and n viruses from generation k in a binary tree, find the deepest generation whose node is an ancestor of all given viruses.Medium4TreeBit manipulation+2No attempts yet1s128 MBJudgeable
RestaurantsEvery city connects by weighted roads and some hold restaurants; report the largest distance from any city to its closest restaurant.Medium4Shortest pathGraph+1No attempts yet1s128 MBJudgeable
ChochlikDecide for each department whether wheels linked by same-direction and opposite-direction belts can all spin without contradiction.Medium4Union-findGraph+1No attempts yet1s512 MBJudgeable
Bajtozja the FrogThe frog hops between stones at most s apart starting from stone p and then dives length s to finish as far from the start as possible.Medium4GraphBFS+1No attempts yet1s512 MBJudgeable
BanquetFind how many round tables are needed by counting the cycles in the left-neighbor links.Medium4GraphDFSNo attempts yet1s512 MBJudgeable
MerchantFind the simple path, possibly empty, in a weighted tree whose edge weights sum to the largest value.Medium4TreeDynamic programming+1No attempts yet1s128 MBJudgeable
Independent ArchitectureCount the wall cells plus the empty cells enclosed by the single closed wall loop in each grid.Medium4BFSMatrixNo attempts yet1s128 MBJudgeable
Indiana Jones Among the ZombiesEvery turn each zombie steps toward chamber 1 along a shortest path, and you find the first turn with more than K arrivals or confirm Indiana survives.Medium4BFSShortest path+1No attempts yet6s128 MBJudgeable
Snow PlowsFind the fewest trails that cover every street exactly once by counting odd-degree intersections in each connected part.Medium4GraphDFSNo attempts yet3s128 MBJudgeable
ZbyszekCheck whether remembered degrees can form a forest by testing that their sum is even and at most twice the dot count minus two.Medium4GraphMath+1No attempts yet2s128 MBJudgeable
ExperimentOrient each undecided corridor so the whole maze stays acyclic, following the smallest-numbered topological order of the fixed corridors.Medium4Topological sortGraph+1No attempts yet3s128 MBJudgeable
PoliticiansSplit up to 18 people with rivalry pairs into two groups with no rival trio in either group and maximize the first group.Medium4Brute forceBit manipulation+1No attempts yet1s128 MBJudgeable
Circle DanceFind the largest want-link cycle in which each girl is disliked by fewer than half of the members.Medium4GraphDFSNo attempts yet1s128 MBJudgeable
DSLRFind the shortest DSLR command string that turns register value A into target B, breaking ties in alphabetical order.Medium4BFSGraphNo attempts yet6s256 MBJudgeable
Escape the Maze with a DrillDecide whether a robot can reach the target on a grid by drilling through at most k walls.Medium4Shortest pathBFS+2No attempts yet1s128 MBJudgeable
Quad TreesBuild the quadtree partition of each binary image and print its level-order bitstream as uppercase hex without leading zeros.Medium4Divide and conquerRecursion+2No attempts yet1s128 MBJudgeable
GnomeSimulate Same-Gnome moves on a letter board, clearing connected groups with gravity and scoring each removal.Medium4SimulationImplementation+2No attempts yet1s128 MBJudgeable
ActorsDecide whether every role can be filled by a distinct available actor who rehearsed it.Medium4GraphDFSNo attempts yet1s128 MBJudgeable
The Same GameSimulate the greedy Same Game strategy that repeatedly removes the largest same-color cluster and applies gravity and column shifts.Medium4SimulationBFS+1No attempts yet1s128 MBJudgeable
Walking While Drinking BeerDecide whether the festival is reachable when each 20-bottle box allows 1000 meters of Manhattan travel between refills at stores.Medium4BFSGraphNo attempts yet1s128 MBJudgeable
TimingApply the directed fractional troop moves for t hours, then add each fortress value to its linked neighbors and report the minimum.Medium4MatrixSimulation+1No attempts yet1s128 MBJudgeable
Hoo's Afraid of the Big Bad Wolf?Find the directed path from X to Y with the largest product of edge safety probabilities, printed rounded to six decimals.Medium4Shortest pathGraphNo attempts yet1s128 MBJudgeable
Flood-ItSimulate greedy flood fills from the top-left corner that pick the color giving the largest connected region and report moves and per-color counts.Medium4SimulationBFS+1No attempts yet2s128 MBJudgeable