[JavaScript] BFS 구현하기

김예진·2021년 1월 2일
0

JavaScript 알고리즘

목록 보기
2/6
post-thumbnail
const [dx, dy] = [[0, 0, 1, -1], [1, -1, 0, 0]];

const bfs = (graph, start) => {
	visit = [];
	queue = [];
	
	visit.push([start[0], start[1]]);
	queue.push(start);
	
	while (queue) {
		[x, y, dist] = queue.shift();
		if (x === n-1 && y === n-1) return dist;
		
		for (let i=0; i<4; i++) {
			const nx = x + dx[i];
			const ny = y + dy[i];
			if (nx < 0 || ny < 0 || nx >= n || ny >= n || graph[nx][ny] === '0') continue;
			
			if (visit.find(v => v[0] === nx && v[1] === ny) === undefined) {
				queue.push([nx, ny, dist + 1]);
				visit.push([nx, ny]);
			}
		}
	}
};

const readline = require("readline");
const rl = readline.createInterface({
	input: process.stdin,
	output: process.stdout
});

let cnt = 0;
let arr = [];
let n;

rl.on("line", function(line) {
	if (cnt !== 0) {
		const input = line.split(' ');
		arr.push(input)
	} else {
		n = parseInt(line);
	}
	cnt++;
}).on("close", function() {
	console.log(bfs(arr, [0, 0, 1]));
	process.exit();
});

문제 출처

0개의 댓글