圖(Graph)是一種用來表示物件之間關係的數據結構。
它由節點(或稱為頂點)和邊組成,節點代表物件,而邊則代表這些物件之間的關係。
圖可分為有向圖和無向圖,具體取決於邊是否有方向。
資料結構圖有許多應用,例如在社交網路、網路路由、計算機科學等領域中。
而今天要介紹的 Breadth-First Search (BFS) 和 Depth-First Search (DFS) 是兩種用於在圖中搜索節點的算法,它們之間有密切的關係,但在搜索過程中的策略不同。
// Breadth-First Search
import java.util.LinkedList
// Graph class
class Graph(val vertices: Int) {
val adjacencyListArray = Array(vertices) { LinkedList<Int>() }
fun addEdge(src: Int, dest: Int) {
adjacencyListArray[src].add(dest)
}
}
class BFS {
fun bfs(graph: Graph, start: Int) {
val visited = BooleanArray(graph.vertices)
val queue = LinkedList<Int>()
visited[start] = true
queue.add(start)
while (queue.size != 0) {
val current = queue.poll()
print("$current ")
val edges = graph.adjacencyListArray[current]
for (edge in edges) {
if (!visited[edge]) {
visited[edge] = true
queue.add(edge)
}
}
}
}
}
// GRAPH
// 0-----1
// | /|
// | / |
// |/ |
// 2-----3
// main function
fun main(args: Array<String>) {
val graph = Graph(4)
graph.addEdge(0, 1)
graph.addEdge(0, 2)
graph.addEdge(1, 2)
graph.addEdge(2, 0)
graph.addEdge(2, 3)
println("Following is Breadth First Traversal " + "(starting from vertex 2)")
val bfs = BFS()
bfs.bfs(graph, 2)
}
BFS(廣度優先搜索):
BFS 適用於廣泛的搜索,並可用於尋找最短路徑
// Depth-First Search
import java.util.LinkedList
// Graph class
class Graph(val vertices: Int) {
val adjacencyListArray = Array(vertices) { LinkedList<Int>() }
fun addEdge(src: Int, dest: Int) {
adjacencyListArray[src].add(dest)
}
}
class DFS {
fun dfs(graph: Graph, start: Int) {
val visited = BooleanArray(graph.vertices)
dfsUtil(graph, start, visited)
}
private fun dfsUtil(graph: Graph, current: Int, visited: BooleanArray) {
visited[current] = true
print("$current ")
val edges = graph.adjacencyListArray[current]
for (edge in edges) {
if (!visited[edge]) {
dfsUtil(graph, edge, visited)
}
}
}
}
// GRAPH
// 0-----1
// | /|
// | / |
// |/ |
// 2-----3
// main function
fun main(args: Array<String>) {
val graph = Graph(4)
graph.addEdge(0, 1)
graph.addEdge(0, 2)
graph.addEdge(1, 2)
graph.addEdge(2, 0)
graph.addEdge(2, 3)
println("Following is Breadth First Traversal " + "(starting from vertex 2)")
val dfs = DFS()
dfs.dfs(graph, 2)
}
DFS(深度優先搜索):
DFS則適用於深度搜索,用於尋找結構或跟蹤路徑
所有 Code 可以在 Github 找到 ~
感謝大家,明天見!!!