樸素Dijkstra演算法模板,dijkstra演算法

來源:互聯網
上載者:User

樸素Dijkstra演算法模板,dijkstra演算法

樸素Dijkstra不需要用到堆,每次找最小值都得遍曆一遍,時間複雜度較高。

點是從編號0到編號n-1的n個點。

以下是模板:

int Dijkstra(int a,int b)   //a是起點,b是終點{    bool visited[maxn];  // 記錄訪問點    int pos = a, min, dist[maxn];  // pos是個標記點,標記每次最小邊對應的點 ,dist記錄起點到各點間最短距離。    for(int i = 0; i < n; i++)    {        dist[i] = map[a][i]; visited[i] = 0;    }    dist[a] = 0; // 自身到自身肯定是0    visited[a] = 1;        // 起點標記已訪問    for(int i = 0; i < n - 1; i++)    // 遍曆之後的n-1個點    {        min = INF;      // min每次都要先定義一個很大的數        for(int j = 0; j < n; j++)            if((!visited[j]) && dist[j] < min)  // 搜尋最小的邊            {                pos = j;         // 搜到進行標記                min = dist[pos];            }if(min == INF)    break;  // 如果最小值沒有被更新說明沒有路和終點相連,就不需要繼續運行了visited[pos] = 1;  // 標記點已訪問        for(int j = 0; j < n; j++)            if(!visited[j] && map[pos][j] > dist[pos] + map[pos][j])                dist[j] = dist[pos] + map[pos][j];   // 更新dist    }    return  dist[b]; // 返回a到b的最短距離                                               }





Dijkstra演算法的原始碼

Dijkstra演算法--c++原始碼--

#include<iostream.h>
void main()
{
int infinity=100,j,i,n,k,t,**w,*s,*p,*d;
cout<<"input the value of n:";
cin>>n;
cout<<endl;

d=new int[n];
s=new int[n];
p=new int[n];
w=new int*[n];
for(i=0;i<n;i++) {w[i]=new int[n];}
for(i=0;i<n;i++)
for(j=0;j<n;j++)
cin>>w[i][j];

for(s[0]=1,i=1;i<n;i++)
{
s[i]=0;d[i]=w[0][i];
if(d[i]<infinity) p[i]=0;
else p[i]=-1;
}

for(i=1;i<n;i++)
{
t=infinity;k=1;
for(j=1;j<n;j++)
if((!s[j])&&(d[j]<t)) {t=d[j];k=j;}
s[k]=1;//point k join the S
for (j=1;j<n;j++)
if((!s[j])&&(d[j]>d[k]+w[k][j]))
{d[j]=d[k]+w[k][j];p[j]=k;}

}
cout<<"從源點到其它頂點的最短距離依次如下:";
for(i=1;i<n;i++) cout<<d[i]<<" ";

}
/*********
頂點個數用n表示,這裡給出的例子n=6
100 1 12 100 100 100
100 100 9 3 100 100
100 100 100 100 5 100
100 100 4 100 13 15
100 100 100 100 100 4
100 100 100 100 100 100
具體例子見 電子工業出版社 《演算法設計技巧與分析》148頁
************/
 
Dijkstra演算法問題

dijkstra演算法的時間複雜度是O(n²),
不妨設為kn²,其中次數小於1的項忽略
k(10×10)=10ms
那麼k(40×40)=16[k×(10×10)]=160ms
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.