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 |
Tags
- 백준 1000번 java
- java
- 개발상식
- 자료구조힙
- heap정렬
- 프렌즈4블록
- 자료구조 트리
- 객체프로그래밍
- 자바
- 카카오기출
- 카카오1차
- 자바문자열
- java method
- 코딩테스트기출
- 공부정리
- 카카오코테
- 프렌즈4블록java
- 카카오코딩테스트
- 백준 1000번
- 프로그래머스
- 객체프로그래밍이란
- 백준 1924번
- 힙정렬자바
- 백준 1924번 java
- 문자열포맷
- 알고리즘
- 코테준비
- heap
- 백준
- Java heap
Archives
- Today
- Total
일단 시작해보는 블로그
[알고리즘_풀이] 프로그래머스 - 단어변환 java 본문
https://programmers.co.kr/learn/courses/30/lessons/43163
코딩테스트 연습 - 단어 변환 | 프로그래머스
두 개의 단어 begin, target과 단어의 집합 words가 있습니다. 아래와 같은 규칙을 이용하여 begin에서 target으로 변환하는 가장 짧은 변환 과정을 찾으려고 합니다. 1. 한 번에 한 개의 알파벳만 바꿀 수 있습니다. 2. words에 있는 단어로만 변환할 수 있습니다. 예를 들어 begin이 hit, target가 cog, words가 [hot,dot,dog,lot,log,cog]라면 hit -> hot -> dot -> dog ->
programmers.co.kr
import java.util.*;
class Solution {
public int solution(String begin, String target, String[] words) {
int answer = 0;
HashMap<String, Node> map = new HashMap<>();
for(int i=0; i<words.length; i++) {
Node in = new Node();
map.put(words[i], in);
}
map.put(begin, new Node());
answer = dfs(begin, target, words, map);
return answer;
}
public int dfs(String begin, String target, String[] words, HashMap<String, Node> map) {
// target이 words에 포함되지 않으면 리턴
if(map.containsKey(target) == false) {
return 0;
}
Stack<String> stack = new Stack<>();
stack.push(begin);
int count = Integer.MAX_VALUE;
while(!stack.isEmpty()) {
String out = stack.pop();
map.get(out).checked = true;
if(out.equals(target)) {
count = Math.min(count, map.get(out).count);
}
// 한 알파벳만 다른 word List 가져오기
stack = getWords(out, words, map, stack, map.get(out).count);
}
return count;
}
public Stack<String> getWords(String key, String[] words, HashMap<String, Node> map, Stack<String> stack, int parent_count) {
int wordLength = key.length();
for(String w: words) {
if(map.get(w).checked == false) {
int count = 0;
for(int i=0; i<wordLength; i++) {
if(w.charAt(i) != key.charAt(i)) {
count++;
}
}
if(count == 1) {
map.get(w).count = parent_count + 1;
stack.add(w);
}
}
}
return stack;
}
class Node {
int count;
boolean checked;
Node() {
this.count = 0;
this.checked = false;
}
}
}
'CS > 알고리즘 풀이' 카테고리의 다른 글
[알고리즘_풀이] 프로그래머스 - 숫자 야구 java (0) | 2020.03.11 |
---|---|
[알고리즘_풀이] 프로그래머스 - 네트워크 java (0) | 2020.03.11 |
[알고리즘_풀이] 프로그래머스 등굣길 java (0) | 2020.03.06 |
[알고리즘_풀이] 프로그래머스 - 가장 먼 노드 java (0) | 2020.03.06 |
알고리즘풀이_ 프로그래머스 타겟넘버 java (0) | 2020.03.04 |
Comments