广度优先遍历(bfs)

  • 从图中某个顶点V0出发,并访问此顶点;
  • 从V0出发,访问V0的各个未曾访问的邻接点W1,W2,…,Wk;然后,依次从W1,W2,…,Wk出发访问各自未被访问的邻接点;
  • 重复步骤2,直到全部顶点都被访问为止

代码中图的结构

广度优先遍历(bfs)_第1张图片

code

/// 节点
class Node {
    var visited:Bool = false
    var value:Int = 0
}

/// 广度优先遍历
///
/// - Parameters:
///   - v: 节点数组
///   - e: 边数组
///   - start: 开始点
func bfs(v:[Node],e:[[Int]],start:Int) {
    var queue:Array = [Node]()
    v[start].visited = true
    queue.append(v[start])
    while queue.count != 0 {
        let headNode = queue[0]
        print(headNode.value)
        queue.remove(at: 0)
        
        //遍历对应的数组
        var tmpArray = e[headNode.value]
        for i in 0..
class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let n = 5
        //节点
        var array:Array = [Node]()
        for i in 0..

console

0
1
2
3
4

时间复杂度

O(n2),n代表顶点的个数

你可能感兴趣的:(广度优先遍历(bfs))