728x90
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
풀이
BFS로 해결한 문제.
문제 이해에 어려움이 있었다.
1️⃣ words 배열을 꼭 순서대로 방문할 필요는 없다.
2️⃣ target은 항상 words의 마지막 요소는 아니다.
3️⃣ target은 words 배열 내에 존재하지 않을 수도 있다.
이 점만 고려하고 풀었다면 쉽게 풀었을 듯 !
전체코드
import java.io.*;
import java.util.*;
class Solution {
public int solution(String begin, String target, String[] words) {
String map[] = new String[words.length + 1];
map[0] = begin;
for(int i=0; i<words.length; i++){
map[i+1] = words[i];
}
int visited[] = new int[map.length];
Queue<Integer> q = new LinkedList<>();
q.offer(0);
while(!q.isEmpty()){
int n = q.poll();
if(map[n].equals(target)){
break;
}
for(int i=1; i<map.length; i++){
int newX = i;
int cnt = 0;
for(int j=0; j<map[newX].length(); j++){
if(map[n].charAt(j) != map[newX].charAt(j)){
cnt++;
}
}
if(visited[newX] == 0 && cnt == 1){
visited[newX] = visited[n]+1;
q.offer(newX);
}else{
continue;
}
}
}
int answer= 0;
int count = 0;
for(int i=0; i<visited.length; i++){
if(map[i].equals(target)){
answer = visited[i];
}else{
count++;
continue;
}
}
if(count == visited.length){
answer = 0;
}
return answer;
}
}
728x90
'코테 > Algorithm' 카테고리의 다른 글
[Programmers] 최고의 집합 (JAVA) (0) | 2024.08.01 |
---|---|
[Programmers] 등굣길 (JAVA) (0) | 2024.07.30 |
[Programmers] 이중우선순위큐 (JAVA) (0) | 2024.07.27 |
[Programmers] 귤 고르기 (JAVA) (0) | 2024.07.25 |
[Programmers] 연속된 부분 수열의 합 (JAVA) (2) | 2024.07.23 |