728x90

๐ตbfs 2๋ฒ ํ์
1. ์์์ ์ ์ ์์ bfs > ๊ฑฐ๋ฆฌ ์ ์ผ ๋จผ๊ฒ ๊ฐ์ฅ ๋์ ์๋ ์ ์ ์ >> ๊ฐ์ฅ ๋์ ์๋ ์ ์ ๊ตฌํ๊ธฐ
2. ๊ฐ์ฅ ๋์ ์๋ ์ ์ ์์ bfs ํ์ > ๋ ์ ์ฌ์ด ์ค ๊ฐ์ฅ ๊ธด ๊ฑฐ๋ฆฌ ๊ตฌํ๊ธฐ ๊ฐ๋ฅ!
import java.util.*;
import java.lang.*;
import java.io.*;
// The main method must be in a class named "Main".
class Main {
static int V; // ์ ์ ๊ฐ์
static int[] dist; // ๊ฑฐ๋ฆฌ ์ ์ฅ
static ArrayList<Node>[] adjList; // ์ธ์ ๋
ธ๋ ์ ์ฅ
static boolean[] visited; // ๋ฐฉ๋ฌธ์ฌ๋ถ ์ ์ฅ
static class Node{
int to;
int w;
public Node(int to, int w){
this.to = to;
this.w = w;
}
}
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
// ์ ์ ๊ฐ์ ์
๋ ฅ๋ฐ๊ธฐ
V = Integer.parseInt(br.readLine());
//์ด๊ธฐ์ค์
dist = new int[V+1]; // ์ ์ ๋ฒํธ 1๋ฒ๋ถํฐ ์์
Arrays.fill(dist, 0);
visited = new boolean[V+1];
adjList = new ArrayList[V+1];
for(int i=1; i<=V; i++){
adjList[i] = new ArrayList<>();
}
// ๊ฐ์ ์ ๋ณด ์
๋ ฅ๋ฐ๊ธฐ
for(int i=1; i<=V;i++){
st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());
while(true){
int b = Integer.parseInt(st.nextToken());
if(b==-1){
break;
}
int c = Integer.parseInt(st.nextToken());
adjList[a].add(new Node(b, c));
}
}
//bfs ์์์ ์ ์ ๋ถํฐ ํ์ > ๊ฐ์ฅ ๋์ ์๋ ์ ์ ๊ตฌํ๊ธฐ
bfs(1);
//๊ฐ์ฅ ๋์ ์๋ ์ ์ ์์ ๊ฑฐ๋ฆฌ ํ์ > ์ต๋๊ฐ ๊ตฌํ๊ธฐ
//dist ์ ์ผ ํฐ ๊ฐ์ธ ์ ์ ๊ตฌํ๊ธฐ
int max = 1;
for(int i=2; i<=V;i++){
//System.out.print(dist[i]+" ");
if(dist[max] < dist[i]){
max = i;
}
}
//dist, visited ๋ฐฐ์ด ์ด๊ธฐํ
Arrays.fill(dist, 0);
Arrays.fill(visited, false);
bfs(max);
//๊ฒฐ๊ณผ ์ถ๋ ฅ > dist ์ ๋ ฌ ํ ์ ์ผ ๋ง์ง๋ง(์ต๋๊ฐ) ์ถ๋ ฅ
Arrays.sort(dist);
System.out.println(dist[V]);
} //main
//bfs
static void bfs(int start){
ArrayDeque<Node> q = new ArrayDeque<>();
dist[start] = 0;
q.offer(new Node(start, 0));
visited[start] = true;
while(!q.isEmpty()){
Node current = q.poll();
for(Node next : adjList[current.to]){
if(visited[next.to]){
continue;
}
visited[next.to] = true;
q.offer(next);
dist[next.to] = dist[current.to] + next.w;
}
} //while๋ฌธ
}
}
'Algorithm > Baekjoon' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
| [๋ฐฑ์ค 15686] ์นํจ ๋ฐฐ๋ฌ (0) | 2025.04.08 |
|---|---|
| [๋ฐฑ์ค 14503] - ์๋ฐ / ๋ฐฉํฅ ๊ณ ๋ คํด์ ์ขํ ์ด๋ํ๊ธฐ (0) | 2025.04.07 |
| [๋ฐฑ์ค 2178] Java - ๊ณต๋ฐฑ ์๋ ์ ์ ์ ๋ ฅ๋ฐ๊ธฐ (0) | 2025.02.26 |
| [๋ฐฑ์ค 1260] Java - dfs, bfs / ๊ฐ๋ฅํ ์์ ์ ์ ๋ฐฉ๋ฌธํ๋ ๊ฒฝ์ฐ (1) | 2025.02.25 |
| [๋ฐฑ์ค 11724] Java - dfs ํ์ (0) | 2025.02.24 |