์ต๋จ ๊ฒฝ๋ก
๐ ๊ฐ์
- ๊ทธ๋ํ ์กฐ๊ฑด์ ๋ฐ๋ผ ์๊ณ ๋ฆฌ์ฆ ์ ํ
- ๊ฐ์ค์น ์์ โ BFS
- ๊ฐ์ค์น ์์ โ ๋ค์ต์คํธ๋ผ(Dijkstra)
- ์์ ๊ฐ์ค์น ๊ฐ๋ฅ โ ๋ฒจ๋ง-ํฌ๋(Bellman-Ford)
- ๋ชจ๋ ์ ์ ์ ์ต๋จ ๊ฑฐ๋ฆฌ โ ํ๋ก์ด๋-์์
(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]);
}
}
}
}
}
}