-
Notifications
You must be signed in to change notification settings - Fork 0
Open
Description
기존 로직 : 변수명 중복 및 간소화를 위해 향상된 for문 사용 및 최적화 필요
...
while (!queue.isEmpty()) {
int current = queue.poll();
if(current-1 >= 0 && !visited[current-1]) {
queue.add(current-1);
time[current-1] = time[current]+1;
visited[current-1] = true;
}if(current+1 <= 100000 && !visited[current+1]) {
queue.add(current+1);
time[current+1] = time[current]+1;
visited[current+1] = true;
} if(current*2 <= 100000 && !visited[current*2]) {
queue.add(current*2);
time[current*2] = time[current]+1;
visited[current*2] = true;
}
}next == K 조건문을 for문안에 넣어 해결하려 했지만, 시작지점이 N==K의 경우 반례가 생김. ( 한 번 이동한 뒤의 위치를 기준으로 비교하기 때문 )
...
...
while (!queue.isEmpty()) {
int current = queue.poll();
int[] nextPositions = {current-1, current+1, current*2};
for(int next: nextPositions) {
if(next >= 0 && next<= 100000 && !visited[next]) {
queue.add(next);
time[next] = time[current]+1;
visited[next] = true;
if(next == K) {
bw.write(String.valueOf(time[next]));
bw.flush();
return;
}
}
}
}queue에서 꺼낸 직후 current를 바로 비교하여 해결
...
while (!queue.isEmpty()) {
int current = queue.poll();
if(current == K) {
bw.write(String.valueOf(time[current]));
bw.flush();
return;
}
int[] nextPositions = {current-1, current+1, current*2};
for(int next: nextPositions) {
if(next >= 0 && next<= 100000 && !visited[next]) {
queue.add(next);
time[next] = time[current]+1;
visited[next] = true;
}
}
}Metadata
Metadata
Assignees
Labels
No labels