๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
2๏ธโƒฃ Java/Problem Solving

[Java Algorithm] ์ˆจ๋ฐ”๊ผญ์งˆ 3 BOJ #13549

by seolhee2750 2022. 8. 8.
๋ฌธ์ œ

https://www.acmicpc.net/problem/13549

 

13549๋ฒˆ: ์ˆจ๋ฐ”๊ผญ์งˆ 3

์ˆ˜๋นˆ์ด๋Š” ๋™์ƒ๊ณผ ์ˆจ๋ฐ”๊ผญ์งˆ์„ ํ•˜๊ณ  ์žˆ๋‹ค. ์ˆ˜๋นˆ์ด๋Š” ํ˜„์žฌ ์  N(0 ≤ N ≤ 100,000)์— ์žˆ๊ณ , ๋™์ƒ์€ ์  K(0 ≤ K ≤ 100,000)์— ์žˆ๋‹ค. ์ˆ˜๋นˆ์ด๋Š” ๊ฑท๊ฑฐ๋‚˜ ์ˆœ๊ฐ„์ด๋™์„ ํ•  ์ˆ˜ ์žˆ๋‹ค. ๋งŒ์•ฝ, ์ˆ˜๋นˆ์ด์˜ ์œ„์น˜๊ฐ€ X์ผ

www.acmicpc.net

 

๋‚ด ๋ฌธ์ œ ํ’€์ด
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.StringTokenizer;

public class Main {
	static Deque<int[]> que;
	static int[] load = new int[100_001];
	static int[] visited = new int[100_001];
	static int n, k;
	
	public static int bfs() {
		while(!que.isEmpty()) {
			int[] now = que.removeFirst();
			int x = now[0];
			int sec = now[1];
			
			int[] cal = {x+1, x-1, x*2};
			
			for(int i = 0; i < 3; i++) {
				if(cal[i] == k) {
					if(i == 2) visited[k] = Math.min(visited[k], sec);
					else visited[k] = Math.min(visited[k], sec+1);
					continue;
				}
				if(cal[i] < 0 || cal[i] >= load.length || visited[cal[i]] <= sec) continue;
				
				if(i == 2) {
					que.add(new int[]{cal[i], sec}); // ์ˆœ๊ฐ„์ด๋™ ํ•˜๋Š” ๊ฒฝ์šฐ ์ดˆ ์ฆ๊ฐ€x
					visited[cal[i]] = sec;
				}
				else {
					que.add(new int[]{cal[i], sec+1}); // ๊ฑธ์–ด๊ฐˆ ๋• 1์ดˆ ์ฆ๊ฐ€
					visited[cal[i]] = sec+1;
				}
			}
		}
		return visited[k];
	}
	
	public static void main(String[] args) throws Exception {
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st;
		
		st = new StringTokenizer(in.readLine());
		n = Integer.parseInt(st.nextToken());
		k = Integer.parseInt(st.nextToken());;
		
		if(n == k) System.out.println(0);
		else {
			load = new int[100_001];
			visited = new int[100_001];
			for(int i = 0; i < visited.length; i++) visited[i] = Integer.MAX_VALUE;
			que = new ArrayDeque<>();
			que.add(new int[]{n, 0});
			System.out.println(bfs());
		}		
	}

}

๐Ÿ‘‰ BFS ๋ฌธ์ œ

visited ๋ฐฐ์—ด์„ ๋ฐฉ๋ฌธ ์ฒดํฌ, ์ตœ์†Ÿ๊ฐ’ ์ €์žฅ์˜ ๋‘ ๊ฐ€์ง€ ์šฉ๋„๋กœ ์‚ฌ์šฉํ•˜์—ฌ ํ’€์ดํ–ˆ๋‹ค.

์ˆœ๊ฐ„์ด๋™ํ•˜๋Š” ๊ฒฝ์šฐ์—๋Š” ์ดˆ๋ฅผ ๋”ํ•ด์ฃผ์ง€ ์•Š์•„์•ผ ํ•œ๋‹ค๋Š” ์ ๋งŒ ์ ์ ˆํžˆ ์ฒ˜๋ฆฌํ•ด์ฃผ๋ฉด ๋˜๋Š” ๋ฌธ์ œ!

 

๐Ÿ’ก ํ”ผ๋“œ๋ฐฑ
  • ์ฒ˜์Œ์—” ๋‹จ์ˆœํžˆ ์ƒ๊ฐํ•ด์„œ visited๋ฅผ boolean์œผ๋กœ ๋งŒ๋“ค๊ณ ,
    ์ฒ˜์Œ์œผ๋กœ ๋™์ƒ์„ ์ฐพ์œผ๋ฉด ๋ฐ”๋กœ return ํ•˜๋„๋ก ํ–ˆ๋Š”๋ฐ, ์ƒ๊ฐํ•ด๋ณด๋‹ˆ ๊ฑธ์–ด๊ฐ”๋Š”์ง€ or ์ˆœ๊ฐ„์ด๋™ํ–ˆ๋Š”์ง€์— ๋”ฐ๋ผ
    ๋จผ์ € ๋„์ฐฉํ–ˆ๋”๋ผ๋„ ๋” ๋งŽ์€ ์‹œ๊ฐ„์ด ๊ฑธ๋ ธ์„ ์ˆ˜ ์žˆ๋‹ค๋Š” ์ ์„ ์ฒดํฌํ•ด์ค˜์•ผ ํ–ˆ๋‹ค. !!
    => visted๋ฅผ intํ˜•์œผ๋กœ ๋ฐ”๊พธ๊ณ , ์ž๋ฆฌ๋งˆ๋‹ค ์ตœ์†Œ ์‹œ๊ฐ„์„ ๊ฐฑ์‹ ํ•ด์ฃผ์–ด ํ•ด๊ฒฐํ–ˆ๋‹ค.

๋Œ“๊ธ€