티스토리 뷰
POINT
조합 Combinations
빈 좌표 배열에서 3개를 뽑는 조합을 사용하여, 장애물을 세운다.
DFS
장애물을 세운 후, 선생님을 상하좌우로 한 칸씩 계속 이동시킨다.
- 장애물을 만나거나 벽에 다다르면, 다른 방향 감시하기
- 학생을 만나면, 감시를 종료하고 결과("NO") 출력하기
문제풀이
const fs = require("fs");
const input = fs.readFileSync("/dev/stdin").toString().trim().split("\n");
const n = Number(input[0]);
// 그래프 생성
let graph = [];
input.slice(1).forEach(ele => {
graph.push(ele.split(" "));
})
// 빈칸, 선생님 좌표 저장
let blankList = [];
let teacherList = [];
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
if (graph[i][j] === "X") {
blankList.push([i, j]);
} else if (graph[i][j] === "T") {
teacherList.push([i, j]);
}
}
}
// 장애물 위치 3개를 뽑는 조합
const objectCombinations = getCombinations(blankList, 3);
let isCheck = true; // 학생이 감시되면 true
for (const [[x1, y1], [x2, y2], [x3, y3]] of objectCombinations) {
// 장애물 설치
graph[x1][y1] = graph[x2][y2] = graph[x3][y3] = "O";
// 선생님 감시 시작 (학생을 만나는지 아닌지 반환)
isCheck = checkStudent(graph, teacherList);
// 선생님이 학생을 만나지 못했으면 중단
if (!isCheck) {
break;
}
graph[x1][y1] = graph[x2][y2] = graph[x3][y3] = "X"; // 장애물 되돌리기
}
if (isCheck) {
console.log("NO");
} else {
console.log("YES");
}
//////////////////////// 함수 구현
function getCombinations(arr, selectNum) {
let result = [];
if (selectNum === 1) {
return arr.map(ele => [ele]);
}
arr.forEach((fixed, index, origin) => {
const rest = arr.slice(index+1);
const combinations = getCombinations(rest, selectNum - 1);
const attached = combinations.map(ele => [fixed, ...ele]);
result.push(...attached);
})
return result;
}
function checkStudent(graph, teacherList) {
const dx = [-1, 1, 0, 0];
const dy = [0, 0, -1, 1];
// 선생님이 이동한 위치
let nx = 0;
let ny = 0;
for (const [x, y] of teacherList) {
// 상하좌우 한 방향씩 계속 이동
for (let i = 0; i < 4; i++) {
// 선생님 원위치
nx = x;
ny = y;
while (true) {
nx += dx[i];
ny += dy[i];
// 그래프 범위를 벗어나면 중단
if (nx < 0 || nx >= n || ny < 0 || ny >= n) {
break;
}
// 장애물을 만나면 중단
if (graph[nx][ny] === "O") {
break;
}
// 학생을 만나면 종료 true
if (graph[nx][ny] === "S") {
return true;
}
}
}
}
return false; // 학생을 만나지 못했으면 false
}
'🧩 코딩테스트' 카테고리의 다른 글
[백준] 14719 빗물 - node.js (1) | 2023.06.13 |
---|---|
[백준] 14888 연산자 끼워넣기 - Node.js (0) | 2023.05.01 |
[백준] 14501 퇴사 - Python (0) | 2022.11.16 |
[백준] 6603 로또 - Python (0) | 2022.11.14 |
[백준] 1182 부분수열의 합 - Python (0) | 2022.11.14 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 감시피하기
- 웅진IT
- flutter
- 프로그래머스
- 코어자바스크립트
- 동기
- fetch
- python
- React-native
- dfs
- 비동기
- React.js
- rn
- p5js
- 판례암기
- Unsplash
- 파이썬
- Spotify
- 다이나믹프로그래밍
- 프로젝트
- DP
- 코테
- React
- 코딩테스트
- 백준
- Python3
- node.js
- 키워드밑줄
- 코드분석
- backtracking
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
29 | 30 |
글 보관함