티스토리 뷰
const filePath = process.platform === "darwin" ? "input.txt" : "/dev/stdin";
let input = require("fs").readFileSync(filePath).toString().split("\n");
// let [n, m, v] = input[0].split(" ").map(Number);
let [n, m, v] = input[0].split(" ").map((element) => {
return Number(element);
});
const graph = [...Array(n + 1)].map(() => Array(n + 1).fill(0));
const visited = Array(n + 1).fill(false);
let dfsResult = [];
let bfsResult = [];
const dfs = (node) => {
visited[node] = true;
dfsResult.push(node);
for (let i = 1; i <= n; i++) {
if (!visited[i] && graph[node][i] === 1) {
dfs(i);
}
}
};
const bfs = (node) => {
const queue = [];
visited[node] = true;
bfsResult.push(node);
queue.push(node);
while (queue.length > 0) {
let current = queue.shift();
for (let i = 1; i <= n; i++) {
if (!visited[i] && graph[current][i] === 1) {
visited[i] = true;
queue.push(i);
bfsResult.push(i);
}
}
}
};
const solution = () => {
// 그래프 만들기
for (let i = 1; i <= m; i++) {
const [a, b] = input[i].split(" ");
graph[a][b] = 1;
graph[b][a] = 1;
}
dfs(v);
console.log(dfsResult.join(" "));
visited.fill(false);
bfs(v);
console.log(bfsResult.join(" "));
};
solution();
최근에 올라온 글
- Total
- Today
- Yesterday
링크