[백준10026_자바스크립트(javascript)] - 적록색약

경이·2024년 6월 10일

𝑩𝑶𝑱 (𝒋𝒔)

목록 보기
61/325

🔴 문제

적록색약


🟡 Sol

const fs = require('fs');
const path = process.platform === 'linux' ? '/dev/stdin' : 'Wiki\\input.txt';
const [n, ...inputs] = fs.readFileSync(path).toString().trim().split('\n');
const graph = inputs.map((it) => it.split(''));
const graphBlind = graph.map((it) => it.map((it) => (it === 'R' ? 'G' : it)));

const nx = [1, -1, 0, 0];
const ny = [0, 0, 1, -1];

function bfs(x, y, map, target) {
  const q = [[x, y]];

  while (q.length != 0) {
    const [x, y] = q.shift();

    for (let i = 0; i < 4; i++) {
      const dx = x + nx[i];
      const dy = y + ny[i];

      if (dx < 0 || dy < 0 || dx >= n || dy >= n) continue;

      if (map[dx][dy] === target) {
        map[dx][dy] = false;
        q.push([dx, dy]);
      }
    }
  }
}

let count = 0;

for (let i = 0; i < n; i++) {
  for (let j = 0; j < n; j++) {
    if (graph[i][j]) {
      bfs(i, j, graph, graph[i][j]);
      count++;
    }
  }
}

console.log(count);

count = 0;

for (let i = 0; i < n; i++) {
  for (let j = 0; j < n; j++) {
    if (graphBlind[i][j]) {
      bfs(i, j, graphBlind, graphBlind[i][j]);
      count++;
    }
  }
}

console.log(count);
const fs = require('fs');
const path = process.platform === 'linux' ? '/dev/stdin' : 'Wiki\\input.txt';
const [n, ...inputs] = fs.readFileSync(path).toString().trim().split('\n');
const graph = inputs.map((it) => it.split(''));
const graphBlind = graph.map((it) => it.map((it) => (it === 'R' ? 'G' : it)));

const nx = [1, -1, 0, 0];
const ny = [0, 0, 1, -1];

function dfs(x, y, map, target) {
  if (x < 0 || y < 0 || x >= n || y >= n) return false;
  if (map[x][y] === target) {
    map[x][y] = false;

    dfs(x + 1, y, map, target);
    dfs(x - 1, y, map, target);
    dfs(x, y + 1, map, target);
    dfs(x, y - 1, map, target);

    return true;
  }
  return false;
}

let count = 0;
for (let i = 0; i < n; i++) {
  for (let j = 0; j < n; j++) {
    if (graph[i][j] === false) continue;
    if (dfs(i, j, graph, 'R') || dfs(i, j, graph, 'G') || dfs(i, j, graph, 'B'))
      count++;
  }
}

console.log(count);

count = 0;
for (let i = 0; i < n; i++) {
  for (let j = 0; j < n; j++) {
    if (graphBlind[i][j] === false) continue;
    if (dfs(i, j, graphBlind, 'B') || dfs(i, j, graphBlind, 'G')) count++;
  }
}

console.log(count);

🟢 풀이

먼저 어떤 방법으로 풀든지 적록색맹일 경우에 R을 G로 바꾼 새로운 맵을 만들어준다.(다른 방법이 있을 수 있겠지만 나는 이렇게 접근했다.)

이후 적록색약과 적록색약이 아닌사람이 봤을 때 두가지 경우를 나누어 for문을 돌려주면 된다. 색깔별로 영역의 수를 구하라는 말은 없었기 때문에 bfs/dfs를 한번 수행하고 난 후 count 변수값을 1 증가시켜줬다.
함수의 매개변수로는 x, y의 좌표값과 지금 어떤 지도로 bfs/dfs를 수행중인지, 그리고 지금 찾아야 하는 색상은 무엇인지를 받아주었다


🔵 Ref

profile
록타르오가르

0개의 댓글