https://programmers.co.kr/learn/courses/30/lessons/12978
์ผ๋ง์ ์ ํ์๋ '๊ฐ์ฅ ๋จผ ๋ ธ๋' ๋ฌธ์ (https://programmingiraffe.tistory.com/30)์ ๋น์ทํ๋ค๊ณ ์๊ฐํด์ bfs๋ก ํ์๋ค. ๊ทธ๋ฐ๋ฐ ์ฑ์ ์ ๋๋ฆฌ๋ฉด 50%์ ํ ์คํธ์ผ์ด์ค๋ง ํต๊ณผํ๋ค.
'๊ฐ์ฅ ๋จผ ๋ ธ๋' ๋ฌธ์ ์์๋ ๋ชจ๋ ๋ ธ๋์ ๊ฐ์ค์น๊ฐ 1์ด์๋๋ฐ, ์ด ๋ฌธ์ ์์๋ ๊ฐ์ค์น๊ฐ ๋ฌ๋ผ ๊ฑฐ์ณ๊ฐ๋ ๊ฒฝ์ฐ ์ต์๊ฐ์ ๊ฐฑ์ ํด์ค์ผํ๋๋ฐ ์๋๋ ๊ฒ ๊ฐ๋ค..
๊ฒฐ๊ตญ ๋ ๋ณต์กํ์ง๋ง ๋ค์ต์คํธ๋ผ ์๊ณ ๋ฆฌ์ฆ์ผ๋ก ํ์ด์ค์ผ ํ๋ค.
BFS๋ก ํผ ํ์ด(๋ชจ๋ tc ํต๊ณผ X)
import java.util.*;
class Solution {
static final int INF = 50000001;
static int[][] graph;
static boolean[] visited;
static int[] dist;
public int solution(int N, int[][] road, int K) {
graph = new int[N + 1][N + 1];
for(int a[] : graph) {
Arrays.fill(a, INF);
}
visited = new boolean[N + 1];
dist = new int[N + 1];
Arrays.fill(dist, Integer.MAX_VALUE);
for(int i = 0; i < road.length; i++) {
int a = road[i][0];
int b = road[i][1];
int c = road[i][2];
graph[a][b] = Math.min(graph[a][b], c);
graph[b][a] = Math.min(graph[b][a], c);
}
bfs(1);
int answer = 0;
for(int i = 1; i < N + 1; i++) {
if(dist[i] <= K) {
answer++;
}
}
return answer;
}
public void bfs(int v) {
Queue<Integer> q = new LinkedList<>();
q.add(v);
visited[v] = true;
dist[1] = 0;
while(!q.isEmpty()) {
int p = q.poll();
for(int i = 1; i < graph.length; i++) {
if(graph[p][i] != INF && !visited[i]) {
q.offer(i);
visited[i] = true;
dist[i] = Math.min(dist[i], dist[p] + graph[p][i]);
}
}
}
}
}
๋ค์ต์คํธ๋ผ ์๊ณ ๋ฆฌ์ฆ
import java.util.*;
class Node implements Comparable<Node> {
int to;
int weight;
Node(int to, int weight) {
this.to = to;
this.weight = weight;
}
@Override
public int compareTo(Node o) {
return Integer.compare(this.weight, o.weight);
}
}
class Solution {
static List<Node>[] list;
static boolean[] visited;
static int[] dist;
public int solution(int N, int[][] road, int K) {
list = new ArrayList[N + 1];
for(int i = 1; i < N + 1; i++) {
list[i] = new ArrayList<>();
}
visited = new boolean[N + 1];
dist = new int[N + 1];
Arrays.fill(dist, Integer.MAX_VALUE);
for(int i = 0; i < road.length; i++) {
int a = road[i][0];
int b = road[i][1];
int c = road[i][2];
list[a].add(new Node(b,c));
list[b].add(new Node(a,c));
}
dijkstra(1);
int answer = 0;
for(int i = 1; i < N + 1; i++) {
if(dist[i] <= K) {
answer++;
}
}
return answer;
}
public void dijkstra(int start) {
Queue<Node> q = new PriorityQueue<>();
q.add(new Node(start,0));
dist[start] = 0;
while(!q.isEmpty()) {
Node node = q.poll();
int to = node.to;
if(visited[to]) {
continue;
} else {
visited[to] = true;
}
for(Node next : list[to]) {
if(dist[next.to] >= dist[to] + next.weight) {
dist[next.to] = dist[to] + next.weight;
q.add(new Node(next.to, dist[next.to]));
}
}
}
}
}
์ฐธ๊ณ
๋ค์ต์คํธ๋ผ ์๊ณ ๋ฆฌ์ฆ https://loosie.tistory.com/146
'Algorithm > ํ๋ก๊ทธ๋๋จธ์ค' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
ํ๋ก๊ทธ๋๋จธ์ค - ์ผ๊ฐ ๋ฌํฝ์ด (0) | 2022.06.20 |
---|---|
ํ๋ก๊ทธ๋๋จธ์ค - ๊ฒ์ ๋งต (0) | 2022.06.14 |
ํ๋ก๊ทธ๋๋จธ์ค - ๋ ๋งต๊ฒ (0) | 2022.06.05 |
ํ๋ก๊ทธ๋๋จธ์ค - ์์ด ๋๋ง์๊ธฐ (0) | 2022.06.04 |
ํ๋ก๊ทธ๋๋จธ์ค - ๋ก๋์ ์ต๊ณ ์์์ ์ต์ ์์ (0) | 2022.04.01 |