let graph
const numberOfNodes = 7
let visited = new Array(numberOfNodes)
const bfs = (node) => {
const queue = []
for (let i = 0; i < visited.length; i++) {
visited[i] = false
}
visited[node] = true
queue.push(node)
while (queue.length) {
let currentNode = queue.shift()
for (let j = 0; j < graph[currentNode].length; j++) {
if (graph[currentNode][j] === 1 && visited[j] === false) {
visited[j] = true
queue.push(j)
}
}
}
}
const createGraph = (numberOfNodes) => {
graph = new Array(numberOfNodes)
for (let i = 0; i < graph.length; i++) {
graph[i] = new Array(numberOfNodes)
}
for (let i = 0; i < graph.length; i++) {
for (let j = 0; j < graph[i].length; j++) {
graph[i][j] = 0
}
}
}
const addEdge = (a, b) => {
for (let i = 0; i < graph.length; i++) {
for (let j = 0; j < graph[i].length; j++) {
if (i === a && j === b) {
graph[i][j] = 1
graph[j][i] = 1
}
}
}
}
createGraph(numOfNodes)
addEdge(1, 2)
addEdge(1, 5)
bfs(1)