10026번: 적록색약
적록색약은 빨간색과 초록색의 차이를 거의 느끼지 못한다. 따라서, 적록색약인 사람이 보는 그림은 아닌 사람이 보는 그림과는 좀 다를 수 있다. 크기가 N×N인 그리드의 각 칸에 R(빨강), G(초록)
www.acmicpc.net
핵심 아이디어
간단한 bfs문제이다.
적록색약일때와 아닐때를 분기 하여 bfs 큐에 넣는 조건으로 사용하면 된다.
적록색약일때 => B/G는 같은 색으로 취급
아닐때 => 각각 다른 색깔로 취급
'use strict';
const { DH_NOT_SUITABLE_GENERATOR } = require('constants');
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
let n = 0;
let board = [];
let visitedRG = [];
let visitedNRG = [];
let cntRG = 0;
let cntNRG = 0;
const direction = [
[-1, 0],
[1, 0],
[0, -1],
[0, 1],
];
const isValidPoint = (x, y, n) => {
if (x >= 0 && y >= 0 && x < n && y < n) {
return true;
}
return false;
};
const bfs = (start, isRG) => {
const q = [start];
const firstChr = board[start[0]][start[1]];
while (q.length > 0) {
const [currX, currY] = q.shift();
for (const [a, b] of direction) {
const [nx, ny] = [currX + a, currY + b];
if (isValidPoint(nx, ny, n)) {
// 적록 색약이면
if (isRG) {
if (!visitedRG[nx][ny]) {
if (
(firstChr === 'R' || firstChr === 'G') &&
(board[nx][ny] === 'R' || board[nx][ny] === 'G')
) {
q.push([nx, ny]);
visitedRG[nx][ny] = 1;
} else if (firstChr === 'B' && board[nx][ny] === 'B') {
q.push([nx, ny]);
visitedRG[nx][ny] = 1;
}
}
} else {
if (!visitedNRG[nx][ny]) {
// 색맹아닌경우
// console.log(firstChr, board[nx][ny]);
if (firstChr === board[nx][ny]) {
// console.log('chk');
q.push([nx, ny]);
visitedNRG[nx][ny] = 1;
}
}
}
}
}
}
};
const solution = function (input) {
n = parseInt(input.shift());
board = input.map((row) => {
return Array.from(row);
});
visitedRG = Array.from({ length: n }, () =>
Array.from({ length: n }, () => 0)
);
visitedNRG = Array.from({ length: n }, () =>
Array.from({ length: n }, () => 0)
);
cntRG = 0;
cntNRG = 0;
for (let row = 0; row < n; row++) {
for (let col = 0; col < n; col++) {
if (!visitedNRG[row][col]) {
cntNRG++;
// console.log(row, col);
visitedNRG[row][col] = 1;
bfs([row, col], false);
}
if (!visitedRG[row][col]) {
cntRG++;
visitedRG[row][col] = 1;
bfs([row, col], true);
}
}
}
// console.log(visitedNRG);
console.log(`${cntNRG} ${cntRG}`);
};
const input = [];
rl.on('line', function (line) {
input.push(line);
}).on('close', function () {
solution(input);
process.exit();
});
'개발 > 알고리즘' 카테고리의 다른 글
[Javascript][BOJ] 1238 파티 (0) | 2020.12.15 |
---|---|
[Javascript][BOJ] 1697 숨바꼭질 (0) | 2020.12.13 |
[Javascript][BOJ] 1012 유기농 배추 (0) | 2020.12.06 |
[Javascript][BOJ] 2667 단지번호 붙이기 (0) | 2020.12.05 |
[Javascript][BOJ] 2606 바이러스 (dfs) (0) | 2020.12.05 |