樸素Dijkstra模板函數

來源:互聯網
上載者:User

標籤: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模板函數

聯繫我們

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