跳转到主要内容

代码

代码

数据结构——Python 中的栈

Python 栈数据结构入门:顺序实现与链式实现、push/pop 速度对比,以及两个应用——中缀转后缀表达式转换器和迷宫求解器。

Teo Parashkevov发布于更新于8 分钟阅读
插图中橙色杯子里叠着一摞白色盘子,旁边是深色二进制数字背景上的文字“Data Structures - Stack”
from random import randint
import sys
import numpy as np
import time
import pandas as pd

定义

栈是一种线性数据结构,其特征是 LIFO(后进先出)原则。它是一个有序的元素集合,元素的添加和移除只发生在一端,称为栈顶。栈严格遵循通过栈顶进行元素插入和移除的策略,这意味着最后加入栈的元素最先被移除。这种结构可以实现为提供内容操作能力的抽象数据类型。

用途

栈因其高效和简单而广泛应用于各个领域。它们常用于解决涉及反转或撤销操作的问题。栈结构在解析表达式、实现递归算法、求值后缀表达式以及通过递归深度优先搜索算法回溯等方面不可或缺。此外,栈在编程语言运行时调用栈的实现中也是基础,使函数调用及其返回地址得以高效存储和管理。栈数据结构的通用性和实用性使其成为算法设计与分析中的基本组件。

顺序栈


定义

顺序栈(也称基于数组的栈)是一种使用底层数组存储元素的栈实现。它维护一个固定大小的数组,元素从一端(通常是栈顶)添加和移除。顺序栈提供高效的随机访问,并支持常数时间的插入和删除操作。然而,顺序栈的大小是固定的,无法动态调整以适应不同数量的元素。

顺序栈的优点

  • 高效的随机访问:由于底层数组表示,顺序栈提供高效的元素随机访问。
  • 常数时间操作:顺序栈的插入和删除操作时间复杂度为常数,非常高效。
  • 空间效率:顺序栈内存利用高效,只需要存储元素本身和固定大小的数组。

顺序栈的缺点

  • 固定大小:顺序栈的大小在初始化时确定,无法动态调整以适应不同数量的元素。如果元素数量超过容量或栈变空,可能导致栈溢出或下溢。
  • 低效的扩容:调整顺序栈大小需要创建新的更大数组并复制所有元素,带来额外的时间复杂度和潜在的内存分配问题。
  • 浪费内存:如果栈没有用完整个容量,为数组未使用部分分配的内存就被浪费了。
  • 可扩展性有限:由于固定大小的特性,顺序栈可能不适合元素数量不可预测或多变的应用,因为它们需要预先确定最大容量。

优点

  • 高效的随机访问
  • 常数时间操作
  • 空间效率

缺点

  • 固定大小
  • 低效的扩容
  • 浪费内存
  • 可扩展性有限

在 Python 中,列表和一些其他数据结构是动态伸缩的。这意味着,严格来说,用列表无法实现真正的顺序栈。主要因为 Python 总会为栈中的下一个元素留出空闲空间。为了绕过这个“缺陷”,我们将在 SequentialStack 类中实现一个自定义函数,告诉我们何时达到了栈初始化时设定的理论 max_size。

SequentialStack 类说明

SequentialStack 类使用 Python 列表实现栈数据结构,功能如下:

初始化

  • __init__(max_size:int):以指定的最大容量初始化栈。
    • data:存储元素的空列表。
    • max_size:栈的最大容量。
    • top_idx:栈顶元素的索引指针(空栈时为 -1)。
    • bottom_idx:栈底元素的索引指针(空栈时为 0)。

魔术方法

  • __len__():返回栈的当前长度(元素个数)。
  • __str__():提供栈的字符串表示,高亮栈顶和栈底元素。

私有方法

  • __reached_max_size():检查栈是否已达到最大容量。

栈操作

  • push(element):在容量允许时将元素加入栈顶。
  • pop():移除并返回栈顶元素。

两个操作都会处理下溢(弹空栈)或上溢(栈满时压入),并抛出相应异常。

属性

  • size:返回栈中当前大小(元素个数)。
  • is_empty:检查栈是否为空。
  • top:返回栈顶元素的索引。
  • bottom:返回栈底元素的索引。

该栈遵循后进先出(LIFO)原则,在支持基本栈操作的同时跟踪大小、空状态以及栈顶和栈底元素的位置。

class SequentialStack():

    def __init__(self, max_size:int):
        self.data       = ['' for i in range(max_size)]
        self.max_size   = max_size
        self.top_idx    = -1
        self.bottom_idx = 0

    def __len__(self):
        return len(self.data)

    def __str__(self):
        output = list()

        if self.top_idx == -1:
            return '[]'

        for idx, elmt in enumerate(self.data):
            if self.top_idx == idx and self.bottom_idx == idx:
                output.append( '[' + str(elmt) + ']' + ' <- top/bottom')
                continue
            elif self.top_idx == idx:
                output.append('[' + str(elmt) + ']' + ' <- top')
            elif self.bottom_idx == idx:
                output.append('[' + str(elmt) + ']' + ' <- bottom')
            else:
                output.append('[' + str(elmt) + ']')

        output = '\n'.join(output[::-1])
        return output

    def __reached_max_size(self):
        ''' We implement this function in order to cope with Pythons dynamic variable growth '''
        return True if self.top_idx == (self.max_size - 1) else False

    def push(self, element):
        if not self.__reached_max_size():
            # self.data.append(element)
            self.data[self.top_idx + 1] = element
            self.top_idx += 1
        else:
            raise Exception('Stack overflow')

    def pop(self):
        if not self.is_empty:
            element = self.data.pop()
            self.top_idx -= 1
            return element
        else:
            raise Exception('Stack is empty')

    @property
    def size(self):
        return len(self.data)

    @property
    def is_empty(self):
        # return True if self.size == 0 else False
        return True if self.top_idx == -1 else False

    @property
    def top(self):
        return self.top_idx

    @property
    def bottom(self):
        return self.bottom_idx

    @property
    def top_element(self):
        return self.data[self.top_idx] if self.top_idx >= 0 else None

    @property
    def bottom_element(self):
        return self.data[self.bottom_idx]
seq_stack_max_size = 10
seq_stack = SequentialStack(seq_stack_max_size)
pushed_sequence_squential_stack = list()
for i in range(seq_stack_max_size):
    tmp_element = randint(10, 100)
    seq_stack.push(tmp_element)
    pushed_sequence_squential_stack.append(tmp_element)

print('Number of elements pushed: ', len(pushed_sequence_squential_stack))
print('Pushed sequendce => ', pushed_sequence_squential_stack, '\n')
print(seq_stack)
print()
Number of elements pushed:  10
Pushed sequendce =>  [87, 41, 88, 29, 65, 69, 74, 44, 100, 19]

[19] <- top
[100]
[44]
[74]
[69]
[65]
[29]
[88]
[41]
[87] <- bottom
popped_sequence_sequential_stack = [seq_stack.pop()for i in range(seq_stack_max_size - randint(2, seq_stack_max_size - 2))]
print('Number of elements popped: ', len(popped_sequence_sequential_stack))
print('Popped sequendce => ', popped_sequence_sequential_stack, '\n')
print(seq_stack)
print()
Number of elements popped:  8
Popped sequendce =>  [19, 100, 44, 74, 69, 65, 29, 88]

[41] <- top
[87] <- bottom

链式栈


定义

链式栈(也称基于链表的栈)是一种使用链表存储元素的栈实现。它由节点组成,每个节点包含一个元素和对下一个节点的引用。栈顶由链表中的第一个节点表示。链式栈在大小方面很灵活,可以动态增长或收缩以适应元素。插入和删除操作很高效,只需操作链表的指针。链式栈可以实现高效的内存利用,但由于存储节点引用,可能带来额外开销。

链式栈的优点:

  • 动态大小:链式栈允许动态大小,元素可以轻松添加或移除,无需扩容或移动元素。
  • 高效的内存利用:链式栈优化了内存利用,只为实际存储的元素分配内存,不像基于数组的栈需要固定大小的分配。
  • 易于实现:实现链式栈相对简单,只需极少的代码,也不需要复杂的扩容策略。
  • 灵活性:链式栈便于实现额外的操作,如复制或合并栈,这在各种应用中很有用。

链式栈的缺点:

  • 指针开销:链式栈中每个元素都需要额外的内存空间存储指针,与基于数组的栈相比会增加开销。
  • 访问速度较慢:访问链式栈中的元素需要遍历节点,与基于数组的栈的直接索引相比访问速度更慢。
  • 额外的内存开销:链式栈为存储指针使用额外内存,与实际存储的数据相比可能带来更高的内存开销。
  • 内存碎片化的可能:如果元素频繁地加入和移除链式栈,随时间推移可能导致内存碎片化,造成内存使用低效。

优点

  • 动态大小
  • 高效的内存利用
  • 易于实现
  • 灵活性

缺点

  • 指针开销
  • 访问速度较慢
  • 额外的内存开销
  • 内存碎片化的可能

LinkedStack 类说明

LinkedStack 类使用 Python 列表实现栈数据结构,功能如下:

初始化

  • __init__():初始化栈。
    • data:存储元素的空列表。
    • top_idx:栈顶元素的索引指针(空栈时为 -1)。
    • bottom_idx:栈底元素的索引指针(空栈时为 0)。

魔术方法

  • __len__():返回栈的当前长度(元素个数)。
  • __str__():提供栈的字符串表示,高亮栈顶和栈底元素。

栈操作

  • push(element):将元素加入栈顶。
  • pop():移除并返回栈顶元素。

两个操作都会处理下溢(弹空栈),并相应更新栈顶索引。

属性

  • size:返回栈中当前大小(元素个数)。
  • is_empty:检查栈是否为空。
  • top:返回栈顶元素的索引。
  • bottom:返回栈底元素的索引。

该栈遵循后进先出(LIFO)原则,支持压入、弹出等基本栈操作,并跟踪栈的大小和空状态。

class Node():
    def __init__(self, data):
        self.data = data
        self.next_node = None

    def __iter__(self):
        tmp_node = self
        return_iterable = list()
        while tmp_node is not None:
            return_iterable.append(tmp_node)
            tmp_node = tmp_node.next_node

        return iter(return_iterable)

    def __str__(self):
        return str(self.data)

    def __len__(self):
        counter = 1
        tmp_node = self
        while tmp_node.next_node is not None:
            counter += 1
            tmp_node = tmp_node.next_node

        return counter

class LinkedNodeStack():

    def __init__(self):
        self.data       = None
        self.top_idx    = -1
        self.bottom_idx = 0

    def __len__(self):
        return 0 if self.data is None else len(self.data)

    def __str__(self):
        output = list()

        if self.top_idx == -1:
            return '[]'

        for idx, elmt in enumerate(self.data):
            if self.top_idx == idx and self.bottom_idx == idx:
                output.append( '[' + str(elmt) + ']' + ' <- top/bottom')
                continue
            elif self.top_idx == idx:
                output.append('[' + str(elmt) + ']' + ' <- top')
            elif self.bottom_idx == idx:
                output.append('[' + str(elmt) + ']' + ' <- bottom')
            else:
                output.append('[' + str(elmt) + ']')

        output = '\n'.join(output[::-1])
        return output

    def push(self, element):
        if self.data is None:
            self.data = Node(element)
            self.top_idx += 1
            return

        tmp_node = Node(element)
        last_node = self.data
        for i in range(self.top):
            last_node = last_node.next_node

        last_node.next_node = tmp_node
        self.top_idx += 1

    def pop(self):
        if self.data is not None:
            tmp_node  = self.data
            prev_node = None
            while tmp_node.next_node is not None:
                prev_node = tmp_node
                tmp_node  = tmp_node.next_node

            if prev_node is not None:
                prev_node.next_node = None
                self.top_idx -= 1
            else:
                self.data = None

            return tmp_node
        else:
            raise Exception('Stack is empty')

    @property
    def size(self):
        return self.__len__()

    @property
    def is_empty(self):
        # return True if self.size == 0 else False
        return True if self.top_idx == -1 else False

    @property
    def top(self):
        return self.top_idx

    @property
    def bottom(self):
        return self.bottom_idx

    @property
    def top_element(self):
        tmp_node  = self.data
        while tmp_node.next_node is not None:
            tmp_node  = tmp_node.next_node
        return tmp_node

    @property
    def bottom_element(self):
        return self.data
linked_node_stack = LinkedNodeStack()
linked_node_stack.push(55)
linked_node_stack.push(6)
linked_node_stack.push(7)
linked_node_stack.push(8)
linked_node_stack.push(9)
linked_node_stack.push(10)
linked_node_stack.push(11)

print("The size of the stack is => ", len(linked_node_stack), '\n')
print(linked_node_stack)
The size of the stack is =>  7

[11] <- top
[10]
[9]
[8]
[7]
[6]
[55] <- bottom
popped_element = linked_node_stack.pop()

print("The size of the stack is => ", len(linked_node_stack))
print("Popped element => ", popped_element, '\n')
print(linked_node_stack)
The size of the stack is =>  6
Popped element =>  11

[10] <- top
[9]
[8]
[7]
[6]
[55] <- bottom
class LinkedStack():

    def __init__(self):
        self.data       = list()
        self.top_idx    = -1
        self.bottom_idx = 0

    def __len__(self):
        return len(self.data)

    def __str__(self):
        output = list()

        if self.top_idx == -1:
            return '[]'

        for idx, elmt in enumerate(self.data):
            if self.top_idx == idx and self.bottom_idx == idx:
                output.append( '[' + str(elmt) + ']' + ' <- top/bottom')
                continue
            elif self.top_idx == idx:
                output.append('[' + str(elmt) + ']' + ' <- top')
            elif self.bottom_idx == idx:
                output.append('[' + str(elmt) + ']' + ' <- bottom')
            else:
                output.append('[' + str(elmt) + ']')

        output = '\n'.join(output[::-1])
        return output

    def push(self, element):
        self.data.append(element)
        self.top_idx += 1

    def pop(self):
        if not self.is_empty:
            element = self.data.pop()
            self.top_idx -= 1
            return element
        else:
            raise Exception('Stack is empty')

    @property
    def size(self):
        return len(self.data)

    @property
    def is_empty(self):
        # return True if self.size == 0 else False
        return True if self.top_idx == -1 else False

    @property
    def top(self):
        return self.top_idx

    @property
    def bottom(self):
        return self.bottom_idx

    @property
    def top_element(self):
        return self.data[-1] if len(self.data) > 0 else None

    @property
    def bottom_element(self):
        return self.data[0] if len(self.data) > 0 else None
linked_stack = LinkedStack()
linked_stack_number_of_elements_to_push = 20
pushed_sequence_linked_stack = list()
for i in range(linked_stack_number_of_elements_to_push):
    tmp_element = randint(10, 100)
    linked_stack.push(tmp_element)
    pushed_sequence_linked_stack.append(tmp_element)

print('Number of elements pushed: ', len(pushed_sequence_linked_stack))
print('Pushed sequendce => ', pushed_sequence_linked_stack, '\n')
print(linked_stack)
print()
Number of elements pushed:  20
Pushed sequendce =>  [58, 78, 83, 78, 36, 74, 56, 62, 89, 11, 15, 66, 24, 45, 61, 58, 95, 19, 36, 59]

[59] <- top
[36]
[19]
[95]
[58]
[61]
[45]
[24]
[66]
[15]
[11]
[89]
[62]
[56]
[74]
[36]
[78]
[83]
[78]
[58] <- bottom
popped_sequence_linked_stack = [linked_stack.pop()for i in range(linked_stack_number_of_elements_to_push - randint(2, linked_stack_number_of_elements_to_push - 2))]
print('Number of elements popped: ', len(popped_sequence_linked_stack))
print('Popped sequendce => ', popped_sequence_linked_stack, '\n')
print(linked_stack)
print()
Number of elements popped:  5
Popped sequendce =>  [59, 36, 19, 95, 58]

[61] <- top
[45]
[24]
[66]
[15]
[11]
[89]
[62]
[56]
[74]
[36]
[78]
[83]
[78]
[58] <- bottom

(测试)push 元素速度对比

def time_push(number_of_iterations, stack_obj):
    time_all_iterations = None
    time_per_operation  = []

    start_time_all_iterations = time.time()
    for i in range(number_of_iterations):
        random_number = randint(0,100)

        start_time_per_operation = time.time()
        stack_obj.push(random_number)
        end_time_per_operation   = time.time()

        delta_t = end_time_per_operation - start_time_per_operation
        time_per_operation.append(delta_t)

    end_time_all_iterations = time.time()

    time_all_iterations = end_time_all_iterations - start_time_all_iterations
    avg_time_per_operation = sum(time_per_operation)/len(time_per_operation)

    return time_all_iterations, avg_time_per_operation
test_number_of_iteratons = 100_000

print('\nTesting Push operation\n')

test_sequential_stack  = SequentialStack(test_push_number_of_iteratons)
test_linked_stack      = LinkedStack()
test_linked_node_stack = LinkedNodeStack()

push_sequential_stack_time_for_all_iterations, push_sequential_stack_avg_time_per_operations   = time_push(test_number_of_iteratons, test_sequential_stack)
push_linked_stack_time_for_all_iterations, push_linked_stack_avg_time_per_operations           = time_push(test_number_of_iteratons, test_linked_stack)
push_linked_node_stack_time_for_all_iterations, push_linked_node_stack_avg_time_per_operations = time_push(test_number_of_iteratons, test_linked_node_stack)

print('\nSequential Stack')
print('Time for all iterations: ', push_sequential_stack_time_for_all_iterations)
print('Avg time per operation:  ', push_sequential_stack_avg_time_per_operations)

print('\nLinked Stack')
print("This stack utilizes Python's in-built list() type. Therefore, it will have the best performance in terms of tme.")
print('Time for all iterations: ', push_linked_stack_time_for_all_iterations)
print('Avg time per operation:  ', linked_stack_avg_time_per_operations)

print('\nLinked Node Stack')
print('Time for all iterations: ', push_linked_node_stack_time_for_all_iterations)
print('Avg time per operation:  ', push_linked_node_stack_avg_time_per_operations)
Testing Push operation


Sequential Stack
Time for all iterations:  0.22549724578857422
Avg time per operation:   7.430005073547363e-07

Linked Stack
This stack utilizes Python's in-built list() type. Therefore, it will have the best performance in terms of tme.
Time for all iterations:  0.1650378704071045
Avg time per operation:   3.8222551345825195e-07

Linked Node Stack
Time for all iterations:  267.0029981136322
Avg time per operation:   0.0026655999803543093

分析迭代性能可以看出,链式(节点)栈的整体性能最差。这主要归因于必须逐节点遍历直到最后一个节点,耗时巨大。就时间复杂度而言,顺序栈因其高效的结构而更优。然而这一优势以更高的空间占用为代价,因为顺序栈需要为数据存储分配大量内存。

考察每次 push 操作的平均耗时,更凸显了顺序栈的优势。它在每次迭代中直接索引为目标对象分配的内存空间,从而实现快速压入。相比之下,链式(节点)栈需要遍历链表中的所有节点才能到达最后一个节点并更新其 next_node 指针,因此性能更慢。

(测试)pop 元素速度对比

def time_pop(number_of_iterations, stack_obj):
    time_all_iterations = None
    time_per_operation  = []

    start_time_all_iterations = time.time()
    for i in range(number_of_iterations):

        start_time_per_operation = time.time()
        stack_obj.pop()
        end_time_per_operation   = time.time()

        delta_t = end_time_per_operation - start_time_per_operation
        time_per_operation.append(delta_t)

    end_time_all_iterations = time.time()

    time_all_iterations = end_time_all_iterations - start_time_all_iterations
    avg_time_per_operation = sum(time_per_operation)/len(time_per_operation)

    return time_all_iterations, avg_time_per_operation
print('\nTesting Pop operation\n')

pop_sequential_stack_time_for_all_iterations, pop_sequential_stack_avg_time_per_operations   = time_pop(test_number_of_iteratons, test_sequential_stack)
pop_linked_stack_time_for_all_iterations, pop_linked_stack_avg_time_per_operations           = time_pop(test_number_of_iteratons, test_linked_stack)
pop_linked_node_stack_time_for_all_iterations, pop_linked_node_stack_avg_time_per_operations = time_pop(test_number_of_iteratons, test_linked_node_stack)

print('\nSequential Stack')
print('Time for all iterations: ', pop_sequential_stack_time_for_all_iterations)
print('Avg time per operation:  ', pop_sequential_stack_avg_time_per_operations)

print('\nLinked Stack')
print("This stack utilizes Python's in-built list() type. Therefore, it will have the best performance in terms of tme.")
print('Time for all iterations: ', pop_linked_stack_time_for_all_iterations)
print('Avg time per operation:  ', pop_linked_stack_avg_time_per_operations)

print('\nLinked Node Stack')
print('Time for all iterations: ', pop_linked_node_stack_time_for_all_iterations)
print('Avg time per operation:  ', pop_linked_node_stack_avg_time_per_operations)
Testing Pop operation


Sequential Stack
Time for all iterations:  0.11483001708984375
Avg time per operation:   8.0641508102417e-07

Linked Stack
This stack utilizes Python's in-built list() type. Therefore, it will have the best performance in terms of tme.
Time for all iterations:  0.07549548149108887
Avg time per operation:   5.283856391906738e-07

Linked Node Stack
Time for all iterations:  348.05520272254944
Avg time per operation:   0.003479842984676361

分析迭代性能可以看出,链式(节点)栈的整体性能最差。这主要归因于必须逐节点遍历直到最后一个节点,耗时巨大。就时间复杂度而言,顺序栈因其高效的结构而更优。然而这一优势以更高的空间占用为代价,因为顺序栈需要为数据存储分配大量内存。

考察每次 pop 操作的平均耗时,更凸显了顺序栈的优势。它在每次迭代中直接索引为目标对象分配的内存空间,从而实现快速操作。相比之下,链式(节点)栈需要遍历链表中的所有节点才能到达倒数第二个节点并更新其 next_node 指针,因此性能更慢。


应用

表达式计算器

  1. 中缀:<operand_1> <operation_symbol> <operand_2>
  2. 前缀:<operation_symbol> <operand_1> <operand_2>
  3. 后缀:<operand_1> <operand_2> <operation_symbol>
operations_priority = dict()
operations_priority['isp'] = dict()
operations_priority['icp'] = dict()

operations_list = ['(', '*', '/', '%', '+', '-', ')']


# ISP
# In Stack Precedence
operations_priority['isp']['#'] = 0
operations_priority['isp']['('] = 1
operations_priority['isp']['*'] = 5
operations_priority['isp']['/'] = 5
operations_priority['isp']['%'] = 5
operations_priority['isp']['+'] = 3
operations_priority['isp']['-'] = 3
operations_priority['isp'][')'] = 6

# ICP
# Incomming Precedence
operations_priority['icp']['#'] = 0
operations_priority['icp']['('] = 6
operations_priority['icp']['*'] = 4
operations_priority['icp']['/'] = 4
operations_priority['icp']['%'] = 4
operations_priority['icp']['+'] = 2
operations_priority['icp']['-'] = 2
operations_priority['icp'][')'] = 1

def infix_to_postfix(expression:str):
    step_count  = 0
    steps_list  = list()
    output_str  = ''

    linked_stack = LinkedStack()
    linked_stack.push('#')

    for expression_character in expression:
        # print('Current Character => ', expression_character)
        stack_top = linked_stack.top_element
        # print('[Before Logic] Top element => ', stack_top)

        if expression_character not in operations_list:
            output_str += expression_character
        else:
            # expression_character is an operation
            if operations_priority['icp'][expression_character] > operations_priority['isp'][stack_top]:
                # print('[icp] > [isp] [PUSH]')
                linked_stack.push(expression_character)
            elif operations_priority['icp'][expression_character] < operations_priority['isp'][stack_top]:
                # print('[icp] < [isp] [POP]')
                popped_element = linked_stack.pop()
                stack_top      = linked_stack.top_element
                output_str += popped_element
                while operations_priority['icp'][expression_character] <= operations_priority['isp'][stack_top]:
                    # print('[icp] < [isp] [POP] until ([icp] > [isp])')
                    if stack_top == '(':
                        linked_stack.pop()
                        break
                    popped_element = linked_stack.pop()
                    stack_top      = linked_stack.top_element
                    output_str += popped_element
            else:
                # print('[icp] == [isp] [POP] until ([icp] > [isp])')
                popped_element = linked_stack.pop()
                while popped_element != '(':
                    output_str += popped_element
                    popped_element = linked_stack.pop()
                else:
                    popped_element = linked_stack.pop()
                    continue

    while linked_stack.top_element != '#':
        output_str += linked_stack.pop()

    return output_str
infix_expression   = 'A+B*(C-D)-E/F'
postfix_expression = infix_to_postfix(infix_expression)

print('Infix   Expression: ', infix_expression)
print('Postfix Expression: ', postfix_expression)
ABCD-*+EF/

迷宫求解器

描述:

问题涉及在一个 MxN 的二维数组表示的迷宫中导航,每个元素为 0(表示可通行的路径)或 1(表示墙)。一个人或实体从指定的入口点出发,目标是到达迷宫出口,只能向八个方向(N、NE、E、SE、S、SW、W、NW)中的相邻元素移动。

算法:

  1. 初始化一个栈数据结构,存储当前正在探索的路径。
  2. 从迷宫入口点开始。
  3. 将起始位置压入栈。
  4. 当栈非空时:
    1. 弹出栈顶元素。
    2. 检查弹出的元素是否为出口点。
      1. 如果是,迷宫已解出;退出算法。
    3. 向全部八个方向探索相邻单元格。
      1. 如果相邻单元格是有效移动(不是墙且在迷宫边界内)且尚未访问过:
        1. 将该单元格压入栈。
        2. 标记该单元格为已访问。

如果栈变空仍未找到出口,则迷宫无解。

说明:

该方法利用深度优先搜索(DFS)策略,沿每条分支尽可能走远再回溯。

栈用于记录走过的路径,使算法在某一位置无法继续移动时能够回溯。

具体实现可能因编程语言和栈与迷宫表示所用的数据结构而异。

maze_matrix = [
    [1 for i in range(0, 17) ],
    [0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1 ],
    [1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 1, 1 ],
    [1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1 ],
    [1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1 ],
    [1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1 ],
    [1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1 ],
    [1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1 ],
    [1, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1 ],
    [1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1 ],
    [1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1 ],
    [1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 1 ],
    [1, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 0 ],
    [1 for i in range(0, 17) ]

]

move_directions = [
    {"direction": "N",   "i": -1, "j":  0},
    {"direction": "NE",  "i": -1, "j":  1},
    {"direction": "E",   "i":  0, "j":  1},
    {"direction": "SE",  "i":  1, "j":  1},
    {"direction": "S",   "i":  1, "j":  0},
    {"direction": "SW",  "i":  1, "j": -1},
    {"direction": "W",   "i":  0, "j": -1},
    {"direction": "NW",  "i": -1, "j": -1},
]
def path_around_wall(maze_matrix, move_directions, maze_width, maze_height, maze_exit_x, maze_exit_y, print_stack=False):
    # Inicialization
    walked_path_mark = [ [0 for i in range(0, 17) ] for j in range(0, 14) ]

    # Preprocessing
    walked_path_mark[1][0] = 1
    _stack = LinkedStack()
    starting_position = {'x':1, 'y':1, 'direction':0}

    _stack.push(starting_position)

    while not _stack.is_empty:
        current_item = _stack.pop()
        i = current_item['x']
        j = current_item['y']
        d = current_item['direction']

        while d < 8:
            g = i + move_directions[d]['i']
            h = j + move_directions[d]['j']
            direction_name = move_directions[d]['direction']

            is_current_direction_a_wall       = True if maze_matrix[g][h] == 1 else False
            has_current_direction_been_walked = True if walked_path_mark[g][h] == 1 else False

            # print(f'Direction is {direction_name} [{d}] < 8')
            # print(f'g: {g} \th: {h}')
            # print(f'in the maze_this is [{maze_matrix[g][h]}]')
            # print(f'is_wall:{is_current_direction_a_wall}')
            # print(f'walked: {has_current_direction_been_walked}')

            if ((g == maze_exit_x) and (h == maze_exit_y)):
                walked_position = {}
                walked_position['x'] = i
                walked_position['y'] = j
                walked_position['direction'] = d

                _stack.push(walked_position)

                final_position = {}
                final_position['x'] = g
                final_position['y'] = h
                final_position['direction'] = 2

                _stack.push(final_position)

                if print_stack:
                    print('Exiting Maze\n')
                    print(_stack)
                return _stack

            if ((g == maze_width) and (h == maze_height)):
                if print_stack:
                    print('Direction Stack\n')
                    print(_stack)
                    print(f"m: {maze_width}\tp: {maze_height}")
                return _stack

            if (not is_current_direction_a_wall) and (not has_current_direction_been_walked):
                walked_path_mark[g][h] = 1
                # print(f'Walking on [{g}][{h}] \t In the maze it is [{maze_matrix[g][h]}]')
                # print(f'Walking on [{g}][{h}]')

                walked_position = {}
                walked_position['x'] = i
                walked_position['y'] = j
                walked_position['direction'] = d

                _stack.push(walked_position)

                i = g
                j = h
                d = 0
            else:
                d += 1

    print('No path in maze')
print_path = [ ['-' for i in range(0, 17) ] for j in range(0, 14) ]
print_path[1][0] = 'o'

path_stack = path_around_wall(
        maze_matrix=maze_matrix,
        move_directions=move_directions,
        maze_width=14,
        maze_height=17,
        maze_exit_x=12,
        maze_exit_y=16)


while not path_stack.is_empty:
    current_position = path_stack.pop()
    _x = current_position['x']
    _y = current_position['y']
    print_path[_x][_y] = 'o'

for l in print_path:
    print(l)
['-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-']
['o', 'o', '-', 'o', 'o', 'o', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-']
['-', '-', 'o', '-', 'o', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-']
['-', '-', '-', '-', 'o', 'o', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-']
['-', '-', '-', 'o', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-']
['-', '-', '-', 'o', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-']
['-', '-', 'o', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-']
['-', '-', 'o', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-']
['-', 'o', '-', '-', '-', '-', 'o', 'o', '-', '-', '-', '-', '-', '-', '-', '-', '-']
['-', '-', 'o', '-', '-', 'o', '-', '-', 'o', '-', '-', '-', '-', '-', 'o', '-', '-']
['-', '-', '-', 'o', 'o', '-', '-', '-', 'o', '-', '-', 'o', 'o', 'o', '-', 'o', '-']
['-', '-', '-', '-', '-', '-', '-', '-', '-', 'o', 'o', '-', '-', '-', '-', 'o', '-']
['-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', 'o']
['-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-']

迷宫求解器的终端动画输出,用 "o" 标记从左侧迷宫入口追踪到右下角出口的路径