寬度/廣度優先搜索(BFS)的代碼實現(轉載)

廣度優先搜索(BFS)的代碼實現(轉載),如果造成侵權立刻刪除該文章

具體講解:具體講解

Python的實現

轉載至CSDN博主 郭暢小渣渣 的《Python實現深度優先與寬度優先搜索算法》,侵權立刪。
網址:https://blog.csdn.net/qq_40276310/article/details/80668401?depth_1-utm_source=distribute.pc_relevant.none-task&utm_source=distribute.pc_relevant.none-task


```python
# -*- coding: utf-8 -*-
# /usr/bin/python
# 作者:郭暢
# 實驗日期:20180612
# Python版本:3.6.4
# 主題:基於深度優先和寬度優先的搜索算法的簡單實現
# 參考書籍:數據結構C語言版(清華大學出版社嚴蔚敏版)
 
from collections import deque    # 線性表的模塊
 
# 首先定義一個創建圖的類,使用鄰接矩陣
class Graph(object):
    def __init__(self, *args, **kwargs):
        self.order = []  # visited order
        self.neighbor = {}
 
    def add_node(self, node):
        key, val = node
        if not isinstance(val, list):
            print('節點輸入時應該爲一個線性表')    # 避免不正確的輸入
        self.neighbor[key] = val
 
    # 寬度優先算法的實現
    def BFS(self, root):
        #首先判斷根節點是否爲空節點
        if root != None:
            search_queue = deque()
            search_queue.append(root)
            visited = []
        else:
            print('root is None')
            return -1
 
        while search_queue:
            person = search_queue.popleft()
            self.order.append(person)
 
            if (not person in visited) and (person in self.neighbor.keys()):
                search_queue += self.neighbor[person]
                visited.append(person)
 
    # 深度優先算法的實現
    def DFS(self, root):
        # 首先判斷根節點是否爲空節點
        if root != None:
            search_queue = deque()
            search_queue.append(root)
 
            visited = []
        else:
            print('root is None')
            return -1
 
        while search_queue:
            person = search_queue.popleft()
            self.order.append(person)
 
            if (not person in visited) and (person in self.neighbor.keys()):
                tmp = self.neighbor[person]
                tmp.reverse()
 
                for index in tmp:
                    search_queue.appendleft(index)
 
                visited.append(person)
 
    def clear(self):
        self.order = []
 
    def node_print(self):
        for index in self.order:
            print(index, end='  ')
 
 
if __name__ == '__main__':
    # 創建一個二叉樹圖
    g = Graph()
    g.add_node(('A', ['B', 'C']))
    g.add_node(('B', ['D', 'E']))
    g.add_node(('C', ['F']))
 
    # 進行寬度優先搜索
    g.BFS('A')
    print('寬度優先搜索:')
    print('  ', end='  ')
    g.node_print()
    g.clear()
 
    # 進行深度優先搜索
    print('\n\n深度優先搜索:')
    print('  ', end='  ')
    g.DFS('A')
    g.node_print()
    print()


JAVA的實現

轉載至CSDN博主 的《Java實現深度優先和寬度優先搜索(圖遍歷)》的博文,侵權立刪。
網址:https://blog.csdn.net/qq_28193019/article/details/89278012

import java.util.*;

/*定義圖中的節點的數據結構*/
class Node {
    int val;                // 節點數據
    List<Node> neighbours;  // 相鄰其他節點

    public Node(int x) {
        val = x;
        neighbours = new ArrayList<Node>();
    }
}

public class Code1 {
    public static void main(String[] args) {
        Node begin = createGraph();
        Set<Node> visited = new HashSet<>();
        System.out.println("DFS:");
        DFS(begin, visited);
        System.out.println("BFS:");
        BFS(begin);
    }

    /* 創建圖,返回一個節點 */
    public static Node createGraph() {
        Node v1 = new Node(1);
        Node v2 = new Node(2);
        Node v3 = new Node(3);
        Node v4 = new Node(4);
        Node v5 = new Node(5);
        Node v6 = new Node(6);
        Node v7 = new Node(7);
        Node v8 = new Node(8);

        v1.neighbours.add(v2);
        v1.neighbours.add(v3);
        v1.neighbours.add(v4);
        v1.neighbours.add(v5);

        v2.neighbours.add(v6);
        v2.neighbours.add(v7);

        v4.neighbours.add(v8);
        return v1;
    }

    /**
     * 深度優先
     *
     * @param v       源頂點
     * @param visited 集合類型,記錄所有已訪問頂點
     */
    public static void DFS(Node v, Set<Node> visited) {
        if (visited.contains(v))
            return;
        else {
            System.out.println("Visit node:" + v.val);
            visited.add(v);
            for (Node next : v.neighbours) {
                DFS(next, visited);
            }
        }
    }

    /**
     * 寬度優先
     *
     * @param v 源頂點,即出發頂點
     */
    public static void BFS(Node v) {
        Set<Node> visited = new HashSet<>();
        Queue<Node> queue = new LinkedList<>();
        queue.offer(v);     // 入隊列
        while (!queue.isEmpty()) {
            Node node = queue.poll();   // 出隊列並刪除
            if (!visited.contains(node)) {
                System.out.println("Visit node:" + node.val);
                visited.add(node);
                for (Node next : node.neighbours) {
                    queue.offer(next);
                }
            }
        }
    }
}

C++的代碼實現

轉載至CSDN博主 cclplus 的博文《廣度優先搜索算法(附C++實現)》,侵權立刪。
網址:https://blog.csdn.net/m0_37772174/article/details/81188732


```cpp
/*
*作者:cclplus
*寫作時間:2018/12/23
*/
 
#include <iostream>
#include <queue>
using namespace std;
 
class tree{
public:
	int num;
	tree * left = nullptr;
	tree * middle = nullptr;
	tree * right = nullptr;
 
	tree(int m) :num(m) {//構造函數
		left = nullptr;
		middle = nullptr;
		right = nullptr;
	}
	tree() :num(0) {//構造函數
		left = nullptr;
		middle = nullptr;
		right = nullptr;
	}
	
	~tree() {}//析構函數
};
queue<tree *> ccl;//聲明一個隊列,用於存儲樹的節點
tree mytree[10];
int ar_tree[8] = { 1,1,1,3,5,3,5,7 };
tree * tree_ptr;
int main() {
	ios::sync_with_stdio(false);
	mytree[1] = tree(1);
	for (int i = 2; i <= 9; i++) {
		mytree[i] = tree(i);//重新構造
		tree_ptr= &mytree[ar_tree[i - 2]];
		if (tree_ptr->left == nullptr) {
			tree_ptr->left = &mytree[i];
		}
		else{
			if (tree_ptr->middle== nullptr) {
				tree_ptr->middle = &mytree[i];
			}
			else {
				tree_ptr->right= &mytree[i];
			}
		}
	}
	//把根節點放入隊列中
	ccl.push(&mytree[1]);
	while (!ccl.empty()) {//當隊列不爲空時,程序運行
		tree_ptr = ccl.front();//讀取節點
		//cout << tree_ptr->num << endl;
		if (tree_ptr->left != nullptr) {
			ccl.push(tree_ptr->left);
		}
		if (tree_ptr->middle != nullptr) {
			ccl.push(tree_ptr->middle);
		}
		if (tree_ptr->right != nullptr) {
			ccl.push(tree_ptr->right);
		}
		cout << tree_ptr->num << " ";
		ccl.pop();
	}
	cout << endl;
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章