티스토리 뷰

https://www.acmicpc.net/problem/2931

 

2931번: 가스관

 

www.acmicpc.net

 

class Node {
	constructor(item) {
		this.item = item;
		this.next = null;
	}
}

class Queue {
	constructor() {
		this.head = null;
		this.tail = null;
		this.length = 0;
	}

	push(item) {
		const node = new Node(item);
		if (this.head == null) {
			this.head = node;
		} else {
			this.tail.next = node;
		}

		this.tail = node;
		this.length += 1;
	}

	pop() {
		const popItem = this.head;
		this.head = this.head.next;
		this.length -= 1;
		return popItem.item;
	}
}

const input = require('fs').readFileSync('./dev/stdin').toString().trim().split('\n');
const [N, M] = input.shift().split(' ').map(Number);
const board = input.map((v) => v.trim().split(''));
const dx = [0, 0, -1, 1];
const dy = [-1, 1, 0, 0];
const pipe = {
	M: [
		[0, 1],
		[0, -1],
		[1, 0],
		[-1, 0],
	],
	'|': [
		[-1, 0],
		[1, 0],
	],
	'-': [
		[0, -1],
		[0, 1],
	],
	'+': [
		[0, 1],
		[0, -1],
		[1, 0],
		[-1, 0],
	],
	1: [
		[1, 0],
		[0, 1],
	],
	2: [
		[-1, 0],
		[0, 1],
	],
	3: [
		[-1, 0],
		[0, -1],
	],
	4: [
		[1, 0],
		[0, -1],
	],
};

let mx;
let my;
for (let i = 0; i < N; i++) {
	for (let j = 0; j < M; j++) {
		if (board[i][j] == 'M') {
			mx = i;
			my = j;
			break;
		}
	}
}
let visited = Array.from(Array(N), () => Array(M).fill(false));
visited[mx][my] = true;
const q = new Queue();
for (let k = 0; k < 4; k++) {
	const nx = mx + dx[k];
	const ny = my + dy[k];
	if (nx < 0 || ny < 0 || nx >= N || ny >= M || board[nx][ny] == '.' || board[nx][ny] == 'Z') continue;
	q.push([nx, ny]);
	visited[nx][ny] = true;
}

let ex;
let ey;
while (q.length > 0) {
	const [x, y] = q.pop();
	const symbol = board[x][y];
	for (let k = 0; k < pipe[symbol].length; k++) {
		const nx = x + pipe[symbol][k][0];
		const ny = y + pipe[symbol][k][1];
		if (nx < 0 || ny < 0 || nx >= N || ny >= M || visited[nx][ny]) continue;
		if (board[nx][ny] == '.') {
			ex = nx;
			ey = ny;
			while (q.length > 0) q.pop();
			break;
		} else {
			q.push([nx, ny]);
			visited[nx][ny] = true;
		}
	}
}

let p = 0;

//상8 하4 좌2 우1

const upX = ex - 1;
const upY = ey;
if (upX >= 0 && upX < N && ['|', '+', '1', '4'].includes(board[upX][upY])) p += 8;

const downX = ex + 1;
const downY = ey;
if (downX >= 0 && downX < N && ['|', '+', '2', '3'].includes(board[downX][downY])) p += 4;

const leftX = ex;
const leftY = ey - 1;
if (leftY >= 0 && leftY < M && ['-', '+', '1', '2'].includes(board[leftX][leftY])) p += 2;

const rightX = ex;
const rightY = ey + 1;
if (rightY >= 0 && rightY < M && ['-', '+', '3', '4'].includes(board[rightX][rightY])) p += 1;

const numToSymole = {
	3: '-',
	5: '1',
	6: '4',
	9: '2',
	10: '3',
	12: '|',
	15: '+',
};

console.log(ex + 1, ey + 1, numToSymole[p]);
728x90
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
글 보관함