具體講解:
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);
}
}
}
}
}