https://programmers.co.kr/learn/courses/30/lessons/42861
코딩테스트 연습 - 섬 연결하기
4 [[0,1,1],[0,2,2],[1,2,5],[1,3,1],[2,3,8]] 4
programmers.co.kr
풀이 : 탐욕 알고리즘 / 프림 알고리즘 / 최소신장트리 찾기
참고 : 2021.09.20 - [알고리즘/알고리즘] - 탐욕 알고리즘 Greedy Algorithm
탐욕 알고리즘 Greedy Algorithm
탐욕 알고리즘 현재 상황에서 가장 좋아보이는 답을 선택하는 방법. 상황마다 최적을 선택하면 전체 결과값도 최적이 될것이라는 가정을 전제로 함. ① 각 단계에 도달할 때 마다, 최적의 결과
mantaray.tistory.com
class Solution {
public int solution(int n, int[][] costs) {
boolean[] isVisited = new boolean[n];
int answer = 0;
int visitedSpotCount = 0;
int[][] graph = new int[n][n];
isVisited[0] = true;
for(int[] c : costs) {
graph[c[0]][c[1]]=c[2];
graph[c[1]][c[0]]=c[2];
}
while(visitedSpotCount<n-1) {
int minWeight = Integer.MAX_VALUE;
int visitedSpot = 0;
for(int i=0; i<n; i++) {
if(isVisited[i]) {
for(int j=0; j<n; j++) {
if(graph[i][j]>0 && !isVisited[j]) {
if(minWeight > graph[i][j]) {
minWeight = graph[i][j];
visitedSpot = j;
}
}
}
}
}
visitedSpotCount++;
answer += minWeight;
isVisited[visitedSpot] = true;
}
return answer;
}
}
'알고리즘 > 코딩테스트' 카테고리의 다른 글
프로그래머스 N으로 표현 (0) | 2021.10.04 |
---|---|
프로그래머스 단속카메라 (0) | 2021.10.01 |
프로그래머스 이중우선순위큐 (0) | 2021.09.28 |
프로그래머스 디스크 컨트롤러 (0) | 2021.09.26 |
프로그래머스 베스트앨범 (0) | 2021.09.25 |