liveBook · Manning

Stack

As explained in Grokking AI Algorithms, Second Edition

A stack is a linear data structure in which elements are added and removed from the same end.

A stack is a linear data structure where the last element added is the first one processed: last in, first out (LIFO). section 2.12

Stacks are useful when an algorithm should follow the newest available choice first, exploring deeply before returning to earlier alternatives. section 2.12

A depth-first search uses a stack to:

Maze search

In a maze, DFS pushes neighboring positions onto the stack. The most recently added position is explored first, carrying the search to leaf-node depth before backtracking. Parent links can reconstruct the path to the start. section 2.12

def run_dfs(maze_game, current_point):
    visited_points = [] #A
    stack = [current_point] #A
    while stack: #B
        next_point = stack.pop() #C
        if not is_in_visited_points(next_point,
        ➥visited_points): #D
            visited_points.append(next_point) #D
            if maze_game
            ➥.get_current_point_value(next_point)
            ➥== '*': #E
                return next_point #E
            else:
                neighbors =
                ➥maze_game.get_neighbors(next_point) #F
                for neighbor in neighbors: #F
                    neighbor.set_parent(next_point) #F
                    stack.append(neighbor) #F
return 'No path to the goal found.'

The listing demonstrates stack initialization, repeated popping, visited tracking, neighbor insertion, and termination. section 2.12

How Grokking AI Algorithms, Second Edition covers it

How deep it goes
Defines LIFO and traces stack operations through DFS, including visited checks, goal tests, and backtracking.
Examples
Demonstrates root-node search, maze movement, neighbor processing, and a DFS implementation listing.
What it assumes
Assumes nodes, neighbors, goals, and parent relationships while explaining stack-driven search step by step.
What you can do after
Build it from scratch by initializing, popping, checking, and appending items in a DFS stack.
How it connects
Connects stacks with depth-first search, graph traversal, maze solving, visited tracking, and path reconstruction.

Also explained in

Compare how 14 books explain stack →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Grokking AI Algorithms, Second Edition. The section links point to the parts of the book it draws on.