广度优先搜索(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;
}