๋ฐ์ํ
https://www.acmicpc.net/problem/1697
๋ฌธ์ ํ์ด
1์ฐจ์ BFS์ด๋ค.
2์ฐจ์ BFS์ check ๋ณ์๋ฅผ node๋ก ์ฌ์ฉํ๋ค.
์ ์ถ์ฝ๋
package baekjoon;
import java.io.IOException;
import java.util.*;
public class Main1697 {
static int length = 100000;
static int[] node = new int[length+1];
static Queue<Integer> queue = new LinkedList<>();
static int goal;
public static void main(String[] args) throws IOException {
Scanner scan = new Scanner(System.in);
int start = scan.nextInt();
goal = scan.nextInt();
int time = bfs(start)-1;
System.out.println(time);
}
private static int bfs(int start) {
queue.offer(start);
node[start] = 1; //0์ด๋ก ํ๋ฉด ๋ฐฉ๋ฌธํ๋์ง ์ ์ ์๊ธฐ๋๋ฌธ์ 1์ด๋ก ๊ธฐ์ฌํ๊ณ , ๊ฒฐ๊ณผ๊ฐ์์ -1 ํ๊ธฐ๋กํ๋ค
while(!queue.isEmpty()){
int temp = queue.poll();
//System.out.print("time : " + node[temp] + ", ํ์ฌ๋
ธ๋ : " + temp + ", ๋ฐฉ๋ฌธ๋
ธ๋ : ");
//์์ง์ผ ์ ์๋ ๋ฐฉ๋ฒ์ ๊ฐ์ง ์
int index = 0;
for (int i = 0; i < 3; i++) {
switch (i){
case 0 : index = temp-1; break;
case 1 : index = temp+1; break;
case 2 : index = temp*2; break;
}
if(index >=0 && index <= length && node[index] == 0){ //๋ฐฉ๋ฌธํ์ง ์์ ๊ณณ์ด๋ผ๋ฉด
//node[index] == 0 ๋ง ํ๋๋ ArrayIndexOutOfBounds๊ฐ ๋ฐ์ํ๋ค.
// index >=0 && index <= length ๋ฅผ ๋ค์ ๋ถ์ฌ์ฃผ์ด๋ ๋์ผํ๊ฒ ์ค๋ฅ๊ฐ ๋ฐ์ํ๋ค.
queue.offer(index);
node[index] = node[temp] + 1;
}
//System.out.print(index + ", ");
if(index == goal){
return node[index];
}
}
//System.out.println();
}
return 0;
}
}
๋ฐ์ํ
'๐ฏ Coding Test' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[๋ฐฑ์ค] 2630๋ฒ ์์ข ์ด ๋ง๋ค๊ธฐ ์๋ฐ (๋ถํ ์ ๋ณต) (0) | 2022.02.22 |
---|---|
[๋ฐฑ์ค] 1012 ์ ๊ธฐ๋๋ฐฐ์ถ ์๋ฐ BFS, DFS (0) | 2022.02.21 |
[๋ฐฑ์ค] 1966 ํ๋ฆฐํฐ ํ + ํ ์คํธ์ผ์ด์ค (0) | 2022.02.11 |
[๋ฐฑ์ค] 9012 ๊ดํธ (0) | 2022.02.11 |
[๋ฐฑ์ค] 10828 ์คํ (๋ฐฐ์ด, LinkedList๋ก ๊ตฌํํด๋ณด๊ธฐ) (0) | 2022.02.10 |