1 / 13

PRIM 알고리즘

PRIM 알고리즘. n=input(' 노드의 갯수를 입력하세요 .'); A = randint(n,n,[1,100]);

brand
Télécharger la présentation

PRIM 알고리즘

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. PRIM 알고리즘

  2. n=input('노드의 갯수를 입력하세요.');A = randint(n,n,[1,100]); for a1=1:n for a2=a1+1:n % if A(a1,a2)>=60 A(a1,a2)=inf; end A(a2,a1)=A(a1,a2); end A(a1,a1)=0; end disp('인접행렬 생성!')Adisp('유망한 집합 P1생성!')P1=ones(1,n) P2=ones(1,n); P3=ones(1,n); P4=ones(1,n-1); for c=1:n-1 min1=inf; for b1=1:n if (A(1,b1)~=0)&&(min1>A(1,b1)) min1=A(1,b1); inx=b1; end end disp('유망한 집합 P1!') P1(1,c+1)=inx for b2=1:n if (A(1,b2)==inf)&&(A(inx,b2)==inf) A(1,b2)=inf; else if A(1,b2)>A(inx,b2) A(1,b2)=A(inx,b2); inx if b2~=inx P2(1,b2)=inx end end end end P3(1,c:n-1)=P2(1,c:n-1); disp('연결노드 P4!') P4(1,c)=P3(1,inx) disp('합친행렬표시') Aend 짜쟌

  3. 전반적 디자인 • 준비 • 인접행렬 생성 • 결과값을 출력할 행렬 생성 • 최소비용 신장 트리 구하기 • 출발점에서 비용이 가장 적게 드는 노드 찾기 • 찾은 노드를 해집합에 합치기

  4. 준비 - 인접행렬 생성 n=input('노드의 갯수를 입력하세요.'); A = randint(n,n,[1,100]); 힘들었다! 노드수가 증가하면 수 범위를 넓히는 것이 좋다. 그렇지 않으면, 같은 비용을 가지는 이음선이 많아져서 후반부에는 노드가 순차적으로 나열되게 된다.

  5. 준비 - 인접행렬 생성 for a1=1:n for a2=a1+1:n if A(a1,a2)>=60 A(a1,a2)=inf; end A(a2,a1)=A(a1,a2); end A(a1,a1)=0; end disp('인접행렬 생성!') A

  6. 준비 - 인접행렬 생성

  7. 준비 - 결과값을 출력할 행렬 생성 • 처음 시작은 노드1이므로 초기값은 1 • P1: 1xn 행렬 (노드 추가 순서) • P2: 1xn 행렬 (해집합 안의 어느 노드에서 연결하는지) • P3: 1xn 행렬 (유망한 노드에 최소비용으로 연결하는 노드) • P4: 1x(n-1) 행렬 (어느 노드에서 연결하는지 최종적으로 나타낸다)

  8. MST구하기 –출발점에서비용이 가장 적게 드는 노드 찾기 • 단순한 2중 for문 사용 • 찾은 최소비용 노드의 인덱스는 P(1,2)부터 차례로 저장된다 - P(1,1)은 1로 초기화 되어 있다

  9. MST구하기 –출발점에서비용이 가장 적게 드는 노드 찾기 disp('유망한 집합 P1생성!') P1=ones(1,n) P2=ones(1,n); P3=ones(1,n); P4=ones(1,n-1);

  10. MST구하기 –출발점에서비용이 가장 적게 드는 노드 찾기 for c=1:n-1 min1=inf; for b1=1:n if (A(1,b1)~=0)&&(min1>A(1,b1)) min1=A(1,b1); inx=b1; end end disp('유망한 집합 P1!') P1(1,c+1)=inx

  11. MST구하기 –찾은 노드를 해집합에 합치기 • 해집합에 들어간 노드는 검색할 노드에서는 뺀다(순환이 생기지 않게). • 추가하려는 노드에 연결된 노드가 여러 개일 때 최소 가중치로 연결된 것 선택 • 그 노드에 연결되어있고, 해집합에 들어있는 노드의 가중치를 비교해서 작은 값을 취하게 하면 위 두 문제를 해결

  12. MST구하기 –찾은 노드를 해집합에 합치기 for c=1:n-1 최소 비용 노드 찾기 for b2=1:n if (A(1,b2)==inf)&&(A(inx,b2)==inf) A(1,b2)=inf; else if A(1,b2)>A(inx,b2) A(1,b2)=A(inx,b2); inx if b2~=inx P2(1,b2)=inx end end end end

  13. MST구하기 –찾은 노드를 해집합에 합치기 P3(1,c:n-1)=P2(1,c:n-1); disp('연결노드 P4!') P4(1,c)=P3(1,inx) disp('합친행렬표시') A end 끝

More Related