xxxxxxxxxx
graph = {
'5' : ['3','7'],
'3' : ['2', '4'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
}
visited = [] # List for visited nodes.
queue = [] #Initialize a queue
def bfs(visited, graph, node): #function for BFS
visited.append(node)
queue.append(node)
while queue: # Creating loop to visit each node
m = queue.pop(0)
print (m, end = " ")
for neighbour in graph[m]:
if neighbour not in visited:
visited.append(neighbour)
queue.append(neighbour)
# Driver Code
print("Following is the Breadth-First Search")
bfs(visited, graph, '5') # function calling
xxxxxxxxxx
remember for breadth first searches, you are putting the vertex of your graph into a queue and that determines the order they are travelled
xxxxxxxxxx
import java.util.*;
public class BreadthFirstSearch {
public static void main(String[] args) {
int numVertices = 7;
List<List<Integer>> graph = new ArrayList<>();
// Initialize the graph
for (int i = 0; i < numVertices; i++) {
graph.add(new ArrayList<>());
}
// Add edges
addEdge(graph, 0, 1);
addEdge(graph, 0, 2);
addEdge(graph, 1, 3);
addEdge(graph, 1, 4);
addEdge(graph, 2, 5);
addEdge(graph, 2, 6);
// Perform BFS traversal
System.out.println("BFS Traversal:");
bfs(graph, 0);
}
public static void addEdge(List<List<Integer>> graph, int u, int v) {
graph.get(u).add(v);
graph.get(v).add(u);
}
public static void bfs(List<List<Integer>> graph, int source) {
int numVertices = graph.size();
boolean[] visited = new boolean[numVertices];
Queue<Integer> queue = new LinkedList<>();
visited[source] = true;
queue.add(source);
while (!queue.isEmpty()) {
int vertex = queue.poll();
System.out.print(vertex + " ");
for (int neighbor : graph.get(vertex)) {
if (!visited[neighbor]) {
visited[neighbor] = true;
queue.add(neighbor);
}
}
}
}
}
Breadth First Search Simply Takes a Data Tree or Nested Arrays Like testData. It sorts through the data and looks for its key value.
xxxxxxxxxx
var testData = [[24,2,432,4,213,4,7,124],[12,412,56,4,63,324,6],[5,3,5436,32,345]]
function breadFirstSearch(key){
for (i = 0; i < testData.length; i++){
for (x = 0; x < testData[i].length; x++){
if(testData[i][x] == key){
console.log("Key Location: "+i+","+x)
}
}
}
}
breadFirstSearch(5)