์ตœ๋‹จ ๊ฒฝ๋กœ

๐Ÿ” ๊ฐœ์š”

  • ๊ทธ๋ž˜ํ”„ ์กฐ๊ฑด์— ๋”ฐ๋ผ ์•Œ๊ณ ๋ฆฌ์ฆ˜ ์„ ํƒ
    1. ๊ฐ€์ค‘์น˜ ์—†์Œ โ†’ BFS
    2. ๊ฐ€์ค‘์น˜ ์–‘์ˆ˜ โ†’ ๋‹ค์ต์ŠคํŠธ๋ผ(Dijkstra)
    3. ์Œ์ˆ˜ ๊ฐ€์ค‘์น˜ ๊ฐ€๋Šฅ โ†’ ๋ฒจ๋งŒ-ํฌ๋“œ(Bellman-Ford)
    4. ๋ชจ๋“  ์ ‘์  ์Œ ์ตœ๋‹จ ๊ฑฐ๋ฆฌ โ†’ ํ”Œ๋กœ์ด๋“œ-์›Œ์…œ(Floyd-Warshall)

๐Ÿ“š ์•Œ๊ณ ๋ฆฌ์ฆ˜ ์ข…๋ฅ˜

1. BFS (๊ฐ€์ค‘์น˜ ์—†๋Š” ์ตœ๋‹จ ๊ฒฝ๋กœ)

  • ์•„์ด๋””์–ด : ๊ฐ„์„ ์˜ ๋น„์šฉ์ด ๋ชจ๋‘ 1์ด๋ผ๋ฉด, BFS๋กœ ํƒ์ƒ‰ ์ˆœ์„œ๊ฐ€ ๊ณง ์ตœ๋‹จ๊ฑฐ๋ฆฌ
class BFSShortestPath {
	static int bfs(int start, int end, List<List<Integer>> graph) {
		int n = graph.size();
		int[] dist = new int[n];
		
		Arrays.fill(dist, -1);
		
		Queue<Integer> q = new LinkedList<>();
		q.offer(start);
		dist[start] = 0;
		
		while(!q.isEmpty()) {
			int cur = q.poll();
			if(cur == end) {
				return dist[cur];
			}
			
			for(int next : graph.get(cur)) {
				if(dist[next] == -1) {
					dist[next] = dist[cur] + 1;
					q.offer(next);
				}
			}
		}
		return -1;
	}
}

2. ๋‹ค์ต์ŠคํŠธ๋ผ ์•Œ๊ณ ๋ฆฌ์ฆ˜ (Dijkstra)

  • ์กฐ๊ฑด : ๊ฐ„์„  ๊ฐ€์ค‘์น˜ >= 0
  • ์•„์ด๋””์–ด : ์‹œ์ž‘์ ์—์„œ ๊ฐ€์žฅ ๊ฐ€๊นŒ์šด ์ •์ ๋ถ€ํ„ฐ ํ™•์ • โ†’ ์ธ์ ‘ ์ •์  ๊ฑฐ๋ฆฌ ๊ฐฑ์‹ 
  • ๊ตฌํ˜„ : ์šฐ์„ ์ˆœ์œ„ ํ(ํž™) ์‚ฌ์šฉ
class Dijkstra {
	static class Node implements Comparable<Node> {
		int v;
		int cost;
		
		Node(int v, int cost) {
			this.v = v;
			this.cost = cost;
		}
		
		public int compareTo(Node o) {
			return this.cost - o.cost;
		}
	}
	
	static int[] dijkstra(int n, List<List<Node>> graph, int start) {
		int[] dist = new int[n+1];
		Arrays.fill(dist, Integer.MAX_VALUE);
		dist[start] = 0;
		
		PriorityQueue<Node> pq = new PriorityQueue<>();
		pq.offer(new Node(start, 0));
		
		while(!pq.isEmpty()) {
			Node cur = pq.poll();
			if(cur.cost > dist[cur.v]) {
				continue;
			}
			
			for(Node next : graph.get(cur.v)) {
				int newCost = cur.cost + next.cost;
				if(newCost < dist[next.v]) {
					dist[next.v] = newCost;
					pq.offer(new Node(next.v, newCost));
				}
			}
		}
		return dist;
	}
}

3. ํ”Œ๋กœ์ด๋“œ-์›Œ์…œ (Floyd-Warshall)

  • ์กฐ๊ฑด : ๋ชจ๋“  ์ •์  ์Œ ์ตœ๋‹จ ๊ฑฐ๋ฆฌ (N์ด ์ž‘์„ ๋•Œ, ๋ณดํ†ต N โ‡ 500)
  • ์•„์ด๋””์–ด : ์ ํ™”์‹ โ†’ dp[i][j] = min(dp[i][j], dp[i][k] + dp[k][j])
class FloydWarshall {
	static void floyd(int n, int[][] dist) {
		for(int k = 1; k <= n; k++) {
			for(int i = 1; i <= n; i++) {
				for(int j = 1; j<= n; j++) {
					if(dist[i][k] != 1e9 && dist[k][j] != 1e9) {
						dist[i][j] = Math.min(dist[i][j], dist[i][k] + dist[k][j]);
					}
				}
			}
		
		}
	}
}