Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 31 |
Tags
- Java
- 점프와 순간이동
- 보이어무어
- 튜플
- 완전 탐색
- 완전탐색
- 최소공배수
- pandas
- HashMap
- Dynamic Programming
- python
- 쿼드압축 후 개수세기
- Stack
- HashSet
- 규칙찾기
- 후위 표기법
- 어려웠던 문제
- 순열
- 메뉴리뉴얼
- 동적계획법
- 영문자 확인
- 문자열
- 반복문
- fragment identifier
- 프로그래머스
- 조합
- dfs
- 에라토스테네스의 체
- 2017 카카오 코드
- 알고리즘
Archives
- Today
- Total
csmoon1010의 SW 블로그
[200425] 깊이/너비우선탐색(DFS, BFS) - 단어변환(level3) 본문
1. 문제이해
- 한 번에 한 개의 알파벳을 바꿔 words에 있는 단어로 변환하면서 target과 같은 단어를 만들기
- 조건에 만족하는 결과가 다음으로 연결되는 "노드"로 생각하면 된다!!
2. 전략
**BFS를 이용 : 최소 단계를 구하는 것이므로 depth가 작아야 된다!!
① Vocab 클래스 : 현재 단계를 함께 저장하기 위해 word와 level을 함께 넣을 클래스가 필요
② BFS 요소 : 큐, check 배열
③ BFS
- 큐가 빈 경우 : 방법을 찾지 못한 경우이므로 answer = 0으로 끝남
- target을 찾은 경우 : 해당 Vocab의 level을 answer로
- 이미 check배열에 있거나 현재 시작노드와 같은 단어인 경우 : continue
- 변환 가능한 단어 찾기 : substring(0, j), substring(j+1, size)들끼리 비교 --> q에 넣고, check해주기
3. 참고사항
- String : "substring"은 subString이 아님을 유의
4. 코드
import java.util.*;
class Solution {
public int solution(String begin, String target, String[] words) {
int answer = 0;
int size = begin.length();
class Vocab{
public String word;
public int level;
Vocab(String w, int l){
this.word = w;
this.level = l;
}
}
//BFS
Queue<Vocab> q = new LinkedList<>();
boolean[] check = new boolean[words.length];
q.add(new Vocab(begin, 0));
Vocab current = null;
if(begin.equals(target)){
answer = 0;
}
while(!q.isEmpty()){
current = q.poll();
if(current.word.equals(target)){ //target을 찾은 경우
answer = current.level;
break;
}
for(int i = 0; i < words.length; i++){
if(check[i] || current.word.equals(words[i])){ //이미 변환했던 경우, 같은 단어인 경우
continue;
}
for(int j = 0; j < size; j++){ //변환 가능한 단어 찾기
if((words[i].substring(0, j)).equals(current.word.substring(0, j))
&& (words[i]. substring(j+1, size)).equals(current.word.substring(j+1, size))){
check[i] = true;
q.add(new Vocab(words[i], current.level + 1));
}
}
}
}
return answer;
}
}
'Coding Test > 프로그래머스' 카테고리의 다른 글
[200507] 2016년 - 연습문제(level1) (0) | 2020.05.07 |
---|---|
[200507] 크레인 인형뽑기 게임 - 2019카카오인턴(level1) (0) | 2020.05.07 |
[200425] 그래프 - 가장 먼 노드(level3) (0) | 2020.04.25 |
[200424] 이분탐색(Binary Search) - 예산(level3) (0) | 2020.04.24 |
[200424] 동적계획법(Dynamic Programming) - 타일장식물(level3) (0) | 2020.04.24 |
Comments