算法 - 图论01(Swift版本)

12 阅读1分钟

图论理论基础

深度优先搜索理论基础

广度优先搜索理论基础

题目1:797. 所有可能的路径

讲解

// ACM模式, 邻接矩阵
func searchPath(n: Int, paths: [[Int]]) {
    var map = Array(repeating: Array(repeating: 0, count: n + 1), count: n + 1)
    for line in paths {
        map[line[0]][line[1]] = 1
    }
    var path = [1]
    var res = [[Int]]()
    func dfs(_ x: Int) {
        if x == n { return res.append(path) }
        for i in 1...n where map[x][i] == 1 {
            path.append(i)
            dfs(i)
            path.removeLast()
        }
    }
    dfs(1)
    res.forEach { print("\( $0.map { String($0) }.joined(separator: " ") )") }
}
searchPath(n: 5, paths: [[1, 3], [3, 5], [1, 2], [2, 4], [4, 5]])

// 核心代码模式, graph相当于邻接表
class Solution {
    func allPathsSourceTarget(_ graph: [[Int]]) -> [[Int]] {
        var res = [[Int]]()
        var path = [0]
        func dfs(_ x: Int) {
            if x == graph.count - 1 {
                res.append(path)
                return
            }
            for i in graph[x] {
                path.append(i) 
                dfs(i)
                path.removeLast()
            }
        }
        dfs(0)    
        return res
    }
}