๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๊ฐœ์ธ๊ณต๋ถ€/Algorithm

[๋ฐฑ์ค€][Node.js] 1260๋ฒˆ : DFS์™€ BFS

by ๐Ÿ‡๋ฐ•๋ด‰๋ด‰๐Ÿ‡ 2021. 6. 15.

์ฒซ์งธ ์ค„์— DFS๋ฅผ ์ˆ˜ํ–‰ํ•œ ๊ฒฐ๊ณผ๋ฅผ, ๊ทธ ๋‹ค์Œ ์ค„์—๋Š” BFS๋ฅผ ์ˆ˜ํ–‰ํ•œ ๊ฒฐ๊ณผ๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค. V๋ถ€ํ„ฐ ๋ฐฉ๋ฌธ๋œ ์ ์„ ์ˆœ์„œ๋Œ€๋กœ ์ถœ๋ ฅํ•˜๋ฉด ๋œ๋‹ค.

 

 

Algorithm

-  DFS์™€ BFS -

 


 

๋ฌธ์ œ

๊ทธ๋ž˜ํ”„๋ฅผ DFS๋กœ ํƒ์ƒ‰ํ•œ ๊ฒฐ๊ณผ์™€ BFS๋กœ ํƒ์ƒ‰ํ•œ ๊ฒฐ๊ณผ๋ฅผ ์ถœ๋ ฅํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค. ๋‹จ, ๋ฐฉ๋ฌธํ•  ์ˆ˜ ์žˆ๋Š” ์ •์ ์ด ์—ฌ๋Ÿฌ ๊ฐœ์ธ ๊ฒฝ์šฐ์—๋Š” ์ •์  ๋ฒˆํ˜ธ๊ฐ€ ์ž‘์€ ๊ฒƒ์„ ๋จผ์ € ๋ฐฉ๋ฌธํ•˜๊ณ , ๋” ์ด์ƒ ๋ฐฉ๋ฌธํ•  ์ˆ˜ ์žˆ๋Š” ์ ์ด ์—†๋Š” ๊ฒฝ์šฐ ์ข…๋ฃŒํ•œ๋‹ค. ์ •์  ๋ฒˆํ˜ธ๋Š” 1๋ฒˆ๋ถ€ํ„ฐ N๋ฒˆ๊นŒ์ง€์ด๋‹ค.

 

์ฒซ์งธ ์ค„์— ์ •์ ์˜ ๊ฐœ์ˆ˜ N(1 ≤ N ≤ 1,000), ๊ฐ„์„ ์˜ ๊ฐœ์ˆ˜ M(1 ≤ M ≤ 10,000), ํƒ์ƒ‰์„ ์‹œ์ž‘ํ•  ์ •์ ์˜ ๋ฒˆํ˜ธ V๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ๋‹ค์Œ M๊ฐœ์˜ ์ค„์—๋Š” ๊ฐ„์„ ์ด ์—ฐ๊ฒฐํ•˜๋Š” ๋‘ ์ •์ ์˜ ๋ฒˆํ˜ธ๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ์–ด๋–ค ๋‘ ์ •์  ์‚ฌ์ด์— ์—ฌ๋Ÿฌ ๊ฐœ์˜ ๊ฐ„์„ ์ด ์žˆ์„ ์ˆ˜ ์žˆ๋‹ค. ์ž…๋ ฅ์œผ๋กœ ์ฃผ์–ด์ง€๋Š” ๊ฐ„์„ ์€ ์–‘๋ฐฉํ–ฅ์ด๋‹ค.

 

์ž…์ถœ๋ ฅ ์˜ˆ์‹œ

์ฒซ์งธ ์ค„์— DFS๋ฅผ ์ˆ˜ํ–‰ํ•œ ๊ฒฐ๊ณผ๋ฅผ, ๊ทธ ๋‹ค์Œ ์ค„์—๋Š” BFS๋ฅผ ์ˆ˜ํ–‰ํ•œ ๊ฒฐ๊ณผ๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค. V๋ถ€ํ„ฐ ๋ฐฉ๋ฌธ๋œ ์ ์„ ์ˆœ์„œ๋Œ€๋กœ ์ถœ๋ ฅํ•˜๋ฉด ๋œ๋‹ค.

 

 

๋ฌธ์ œ ํ’€๊ธฐ

let DFS = function (num) {
	visitedDfs[num] = true;
	dfsResult.push(num);

	for (let i = 1; i < graph.length; i++) {
		if (graph[num][i] === 1 && visitedDfs[i] === false) {
			DFS(i);
		}
  }
  return;
};

let BFS = function (num) {
	let queue = [];
	queue.push(num);
	bfsResult.push(num);

  while (queue.length !== 0) {
    let shiftQueue = queue.shift()
    visitedBfs[shiftQueue] = true;
    
    for (let i = 1; i < graph.length; i++) {
      if (graph[shiftQueue][i] === 1 && visitedBfs[i] === false) {
        visitedBfs[i] = true;
        queue.push(i);
        bfsResult.push(i);
      }
    }
  }
  return;
};

const readline = require("readline");
const rl = readline.createInterface({
	input: process.stdin,
	output: process.stdout,
});
let input = [];
let graph = [];
let visitedDfs = [];
let visitedBfs = [];
let dfsResult = [];
let bfsResult = [];

rl.on("line", function (line) {
	input.push(line.toString());
}).on("close", function () {
	let [node, edge, num] = input
		.shift()
		.split(" ")
		.map((el) => Number(el));
	graph = Array.from(Array(node + 1), () => Array(node + 1).fill(0));

	for (let i of input) {
		let [x, y] = i.split(" ").map((el) => Number(el));
		graph[x][y] = 1;
		graph[y][x] = 1;
	}

	visitedDfs = new Array(node + 1).fill(false);
	visitedBfs = new Array(node + 1).fill(false);
	DFS(num);
	BFS(num);

	console.log(dfsResult.join(" ") + "\n" + bfsResult.join(" "));
	process.exit();
});

 

 

 

๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€