Dijkstra演算法 單源最短路徑

來源:互聯網
上載者:User

/*</p><p>0 6 1 5 0 0<br />6 0 5 0 3 0<br />1 5 0 5 6 4<br />5 0 5 0 0 2<br />0 3 6 0 0 6<br />0 0 4 2 6 0</p><p>*/<br />#include<iostream><br />using namespace std;</p><p>#define N 6//節點數<br />const int MaxNum = 10000; //邊權最大值</p><p>int nodes[N][N] = {{0,6,1,5,0,0},{6,0,5,0,3,0},{1,5,0,5,6,4},{5,0,5,0,0,2},{0,3,6,0,0,6},{0,0,4,2,6,0}};<br />int dist[N], state[N], path[N];</p><p>int FindMin() {<br />int minnode = -1, min = MaxNum;<br />for(int i=0; i<N; i++)<br />if((dist[i]<min) && !state[i]) {<br />min = dist[i];<br />minnode = i;<br />}<br />return minnode;<br />}</p><p>int main() {<br />int i, j, done;<br />memset(state, 0, sizeof(state));<br />memset(path, 0, sizeof(path));<br />for(i=0; i<N; i++)<br />for(j=0; j<N; j++)<br />if(nodes[i][j]==0)<br />nodes[i][j] = MaxNum;<br />for(i=0; i<N; i++)<br />dist[i] = nodes[0][i];<br />state[0] = 1;<br />done = 1;</p><p>while(done<N) {<br />int node = FindMin();<br />if(node!=-1) {<br />done ++;<br />state[node] = 1;<br />for(i=0; i<N; i++)<br />if((dist[i]>(dist[node]+nodes[node][i])) && !state[i]) {<br />dist[i] = dist[node]+nodes[node][i];<br />path[i] = node;<br />}<br />}<br />else<br />break;<br />}</p><p>for(i=0; i<N; i++) {<br />if(dist[i] == MaxNum)<br />cout<<-1;<br />else<br />cout<<dist[i];<br />if(i==N-1)<br />cout<<endl;<br />else<br />cout<<" ";<br />}</p><p>int tmp[N], p=0, q;<br />for(i=1; i<N; i++) {<br />printf("到 %d 的最短路徑: ", i);<br />q = i;<br />p = 0;<br />while(path[q]){<br />tmp[p++] = path[q];<br />q = path[q];<br />}<br />printf("0->");<br />for(j=p-1; j>=0; j--)<br />printf("%d->", tmp[j]);<br />printf("%d/n", i);<br />}<br />return 0;<br />}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.