[JavaScript] 구름 - 나이트의 이동

김예진·2021년 1월 2일
0

코딩 테스트

목록 보기
29/42
const [dx, dy] = [[-2, -1, 1, 2, -2, -1, 1, 2], [-1, -2, -2, -1, 1, 2, 2, 1]];

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

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

let count = 0;
let n;
let now, dest;

rl.on("line", function(line) {
	if (count === 0) {
		n = line;
	} else if (count === 1) {
		now = line.split(' ').map(x=>+x);
	} else {
		dest = line.split(' ').map(x=>+x);
	}
	count++;
}).on("close", function() {
	console.log(bfs([now[0], now[1], 0], dest));
	process.exit();
});

문제출처

0개의 댓글