在 python 中优化 DFS

Optimizing DFS in python

我正在学习算法并正在做这个 problem,它正在寻找区域的数量。我尝试使用 python 进行深度优先搜索,但出现调用堆栈超出错误。谁能告诉我我的实施有什么缺陷以及如何克服它?代码是:

def findCircleNum(A):

    count = 0

    def dfs(row, column):
        if row < 0 or column >= len(A[0]) or row >= len(A) or column < 0:
            return

        if A[row][column] == 0:
            return

        A[row][column] = 0

        for i in range(row-1, row+2):
            if i >= 0 and i<len(A) and A[i][column] == 1:
                dfs(i, column)
        for i in range(column-1, column+2):
            if i >= 0 and i<len(A[0]) and A[row][i] == 1:
                dfs(row, i)




    for row in range(len(A)):
        for column in range(len(A[0])):
            if A[row][column] == 1:
                dfs(row, column)
                count += 1


    return count


findCircleNum(m)

它失败的输入是全 1 的 100x100 矩阵

得到的错误是:

RuntimeError: maximum recursion depth exceeded

谢谢!

为什么不在用集合跟踪访问过的顶点(学生)的同时做一个标准的 DFS?问题陈述说矩阵的最大大小为 200x200,因此假设它为 1000,您不必担心递归限制。使用集合进行跟踪也会使代码更简单:

def findCircleNum(A):
    count = 0
    visited = set()

    def dfs(student):
        if student in visited:
            return

        visited.add(student)
        for i, friend in enumerate(A[student]):
            if friend:
                dfs(i)

    for student in range(len(A)):
        # Note we want to track circles, student without any friend won't count
        if student not in visited and any(A[student]):
            dfs(student)
            count += 1

    return count

EDIT 有问题的代码看起来像是在进行 DFS 时将边视为顶点。这也可以解释递归深度的问题,因为具有循环但没有多边的 100 个顶点的无向图具有最大 (100 * 101) / 2 = 5050 条边。