818. Race Car
제가 먼저 level Order BFS의 해법을 썼는데 답안인 DP와 BFS2의 해법을 자세히 보고 싶지 않아요. 이 문제는 너무 어려워요.
class Solution {
public int racecar(int target) {
Map> map = new HashMap<>();
map.putIfAbsent(0, new HashSet());
map.get(0).add(1);
Queue queue = new LinkedList<>();
queue.offer(new State(0, 1));
int level = 0;
if (target == 0) return 0;
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
State st = queue.poll();
if (st.pos > target * 2 || st.pos < target * -1) continue;
//A
int nextPos = st.pos + st.speed;
int nextSpeed = st.speed * 2;
map.putIfAbsent(nextPos, new HashSet<>());
if (map.get(nextPos).contains(nextSpeed)) continue;
if (nextPos == target) return level + 1;
map.get(nextPos).add(nextSpeed);
queue.offer(new State(nextPos, nextSpeed));
//R
nextPos = st.pos;
nextSpeed = st.speed > 0 ? -1 : 1;
if (map.get(nextPos).contains(nextSpeed)) continue;
map.get(nextPos).add(nextSpeed);
queue.offer(new State(nextPos, nextSpeed));
}
level++;
}
return -1;
}
}
class State {
int pos;
int speed;
public State(int pos, int speed) {
this.pos = pos;
this.speed = speed;
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.