Question
Test Case 1
Shell
복사
Test Case 2
Shell
복사
Solve
function bfs(n, m, edges, s) {
// Write your code here
const graph = {};
for(let edge of edges) {
let [src, dest] = edge;
if (!graph[src]) {
graph[src] = [];
}
if(!graph[dest]) {
graph[dest] = [];
}
graph[src].push(dest);
graph[dest].push(src);
}
const distances = Array(n + 1).fill(-1);
const visited = new Set();
const queue = [];
queue.push(s);
visited.add(s);
distances[s] = 0;
let level = 1;
while(queue.length > 0) {
for (let i = queue.length; i > 0; i -= 1) {
const current = queue.shift();
if(graph[current]) {
for (let child of graph[current]) {
if (!visited.has(child)) {
visited.add(child);
distances[child] = 6 * level;
queue.push(child);
}
}
}
}
level += 1;
}
return [...distances.slice(1, s), ...distances.slice(s + 1)];
}
JavaScript
복사
실행시간 : ms