본문 바로가기
알고리즘/이론 및 팁

프림 알고리즘

by 김어찐 2021. 8. 25.
728x90
package day12;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;

public class MSTPrimTest {

	public static void main(String[] args) throws NumberFormatException, IOException {
		System.setIn(new FileInputStream("prim_input.txt"));
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int N = Integer.parseInt(br.readLine());
		int[][] adjMatrix = new int[N][N];
		
		boolean[] visited = new boolean[N];
		int[] minEdge = new int[N];
		
		StringTokenizer st = null;
		
		for (int i = 0; i < N; i++) {
			st = new StringTokenizer(br.readLine()," ");
			for (int j = 0; j < N; j++) {
				adjMatrix[i][j] = Integer.parseInt(st.nextToken());
				
			}
			minEdge[i]=Integer.MAX_VALUE;
			
		}
		int result = 0;
		minEdge[0] = 0;
		for (int i = 0; i < N; i++) {
			// 최솟값, 정점 초기화
			int min = Integer.MAX_VALUE;
			int minVertex =-1;
			
			// 방문하지 않고 정점으로 가장 짦은 경로 선택
			for (int j = 0; j < N; j++) {
				if(!visited[j] && min>minEdge[j]) {
					min = minEdge[j];
					minVertex = j;
				}
			}
			
			// 가장 가중치 적은 노드 방문 체크
			visited[minVertex] = true;
			result+=min;
			
			// 방문한적 없고, 갈 수 있고,
			// 현재 정점부터 갈수있는 노드 가중치가 minEdge의 가중치 보다 작으면 업데이트
			for(int j =0;j<N;j++) {
				if(!visited[j] && adjMatrix[minVertex][j]!=0 && minEdge[j]>adjMatrix[minVertex][j]) {
					minEdge[j]=adjMatrix[minVertex][j];
				}
			}
			
		}
		System.out.println(Arrays.toString(minEdge));
		System.out.println(result);
	}

}
728x90

'알고리즘 > 이론 및 팁' 카테고리의 다른 글

최장 증가 부분수열 (이진탐색)  (0) 2021.09.16
최대 공약수  (0) 2021.09.05