-
[Javascript] 백준 1987 알파벳Algorithm/Problem Solving 2023. 3. 9. 14:12
https://www.acmicpc.net/problem/1987
1987번: 알파벳
세로 R칸, 가로 C칸으로 된 표 모양의 보드가 있다. 보드의 각 칸에는 대문자 알파벳이 하나씩 적혀 있고, 좌측 상단 칸 (1행 1열) 에는 말이 놓여 있다. 말은 상하좌우로 인접한 네 칸 중의 한 칸으
www.acmicpc.net
전형적인 DFS 문제이다.
조금 응용된 부분은 DFS 함수 인자에 지금까지의 알파벳을 set에 담아서 넘겨준다는 점이 있다.
let input = require('fs').readFileSync(__dirname+'/example.txt').toString().trim().split('\n'); let count = 0; const [N, M] = input[count++].split(' ').map(Number); const dy = [ -1, 1, 0, 0 ]; const dx = [ 0, 0, -1, 1 ] let graph = []; let answer = -Infinity; for(let i=0; i<N; i++){ // 입력값 2차원 배열로 만들기 graph.push(input[count++].split('')); } const DFS = (y, x, crnt_set) => { if(crnt_set.size > answer){ answer = crnt_set.size; } for(let i=0; i<4; i++){ const next_y = y + dy[i]; const next_x = x + dx[i]; if(next_y >= 0 && next_y < N && next_x >= 0 && next_x < M){ if(!crnt_set.has(graph[next_y][next_x])){ // set에 없는 알파벳일 경우 crnt_set.add(graph[next_y][next_x]) DFS(next_y, next_x, crnt_set); crnt_set.delete(graph[next_y][next_x]) } } } } DFS(0, 0, new Set(graph[0][0])); console.log(answer);
시행착오를 겪은 부분이 있는데
if(next_y >= 0 && next_y < N && next_x >= 0 && next_x < M){ if(!crnt_set.has(graph[next_y][next_x])){ // set에 없는 알파벳일 경우 crnt_set.add(graph[next_y][next_x]) DFS(next_y, next_x, crnt_set); crnt_set.delete(graph[next_y][next_x]) } }
위의 코드 부분을
if(next_y >= 0 && next_y < N && next_x >= 0 && next_x < M){ if(!crnt_set.has(graph[next_y][next_x])){ // set에 없는 알파벳일 경우 DFS(next_y, next_x, crnt_set.add(graph[next_y][next_x])); } }
이와 같이 했는데, 다른 방향으로 흘러갔다.
나중에 같은 실수하지 않도록 기억하자.
'Algorithm > Problem Solving' 카테고리의 다른 글
[ PS ] 공원 산책 (1) 2023.11.16 [ PS ] 프로그래머스 LV2 리코쳇 로봇 (0) 2023.07.05 [Javascript] 프로그래머스 LV2 귤 고르기 (0) 2022.11.24 [Javascript][Python] 프로그래머스 LV2 큰 수 만들기 (0) 2022.11.15 [Python] 프로그래머스LV2 타겟 넘버 (0) 2022.11.01