最短路徑演算法之五——鄰接表

來源:互聯網
上載者:User

標籤:style   blog   http   color   使用   strong   

鄰接表

  鄰接矩陣來儲存圖的資訊相對於非完全圖,會浪費大量的空間,同時在求最短路徑的時候也會有多餘的計算浪費時間。

  使用鄰接表可以節約這些浪費的時間。

  這裡介紹的是用數組類比的鄰接表:

  定義begin[MAXN],end[MAXN],dis[MAXN],first[MAXN],next[MAXN]五個數組。

  例子描述如下:

    4 5

    1 4 9

    4 3 8

    1 2 5

    2 4 6

    1 3 7

Step1:

 

1

2

3

4

5

begin

 

 

 

 

 

end

 

 

 

 

 

dis

 

 

 

 

 

first

-1

-1

-1

-1

-1

next

 

 

 

 

 

Step2:

 

1

2

3

4

5

begin

1

 

 

 

 

end

4

 

 

 

 

dis

9

 

 

 

 

first

1

-1

-1

-1

-1

next

-1

 

 

 

 

Step3:

 

1

2

3

4

5

begin

1

4

 

 

 

end

4

3

 

 

 

dis

9

8

 

 

 

first

1

-1

-1

2

-1

next

-1

-1

 

 

 

Step4:

 

1

2

3

4

5

begin

1

4

1

 

 

end

4

3

2

 

 

dis

9

8

5

 

 

first

3

-1

-1

2

-1

next

-1

-1

1

 

 

Step5:

 

1

2

3

4

5

begin

1

4

1

2

 

end

4

3

2

4

 

dis

9

8

5

6

 

first

3

4

-1

2

-1

next

-1

-1

1

-1

 

Step6:

 

1

2

3

4

5

begin

1

4

1

2

1

end

4

3

2

4

3

dis

9

8

5

6

7

first

5

4

-1

2

-1

next

-1

-1

1

-1

3

建立鄰接表:

 1 nt n,m,i; 2 int begin[6],end[6],dis[6]; 3 int first[6],next[6]; 4 scanf("%d %d",&n,&m); 5 //初始化first數組 6 for(i=1;i<=n;i++) 7     first[i]=-1; 8 for(i=1;i<=m;i++) 9 {10     scanf("%d %d %d",&begin[i],&end[i],&dis[i]);11     next[i]=first[begin[i]];12     first[begin[i]]=i;13 }

遍曆1號頂點所有邊:

 

1 k=first[1];2 while(k!=-1)3 {4     printf("%d %d %d\n",begin[k],end[k],dis[k]);5     k=next[k];6 }

 

 

 

聯繫我們

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