230923 부대복귀

Jongleee·2023년 9월 23일
0

TIL

목록 보기
372/737
private int[] distances;
private List<Integer>[] routes;
private int limit = 1000000;

public int[] solution(int n, int[][] roads, int[] sources, int destination) {
	initializeGraph(n, roads);
	distances = new int[n + 1];
	Arrays.fill(distances, limit);

	bfs(destination);

	int[] answer = new int[sources.length];
	for (int i = 0; i < sources.length; i++) {
		answer[i] = (distances[sources[i]] < limit) ? distances[sources[i]] : -1;
	}
	return answer;
}

private void initializeGraph(int n, int[][] roads) {
	routes = new ArrayList[n + 1];
	for (int i = 0; i <= n; i++) {
		routes[i] = new ArrayList<>();
	}
	for (int[] road : roads) {
		int start = road[0];
		int end = road[1];
		routes[start].add(end);
		routes[end].add(start);
	}
}

private void bfs(int destination) {
	Queue<Integer> queue = new LinkedList<>();
	queue.add(destination);
	distances[destination] = 0;

	while (!queue.isEmpty()) {
		int current = queue.poll();

		for (int next : routes[current]) {
			if (distances[next] > distances[current] + 1) {
				distances[next] = distances[current] + 1;
				queue.add(next);
			}
		}
	}
}

출처:https://school.programmers.co.kr/learn/courses/30/lessons/132266

0개의 댓글