5 to the shortest path algorithm-the adjacent table

Source: Internet
Author: User

Adjacent table

Compared with a non-full graph, the use of an adjacent matrix to store Graph Information wastes a lot of space. At the same time, there will be excessive computing waste of time when finding the shortest path.

Using an adjacent table can save these waste of time.

The following describes the adjacent tables simulated by Arrays:

Define the begin [maxn], end [maxn], DIS [maxn], first [maxn], and next [maxn] arrays.

The example is described as follows:

4 5

1 4 9

4 3 8

1 2 5

2 4 6

1 3 7

Step 1:

 

1

2

3

4

5

Begin

 

 

 

 

 

End

 

 

 

 

 

DIS

 

 

 

 

 

First

-1

-1

-1

-1

-1

Next

 

 

 

 

 

Step 2:

 

1

2

3

4

5

Begin

1

 

 

 

 

End

4

 

 

 

 

DIS

9

 

 

 

 

First

1

-1

-1

-1

-1

Next

-1

 

 

 

 

Step 3:

 

1

2

3

4

5

Begin

1

4

 

 

 

End

4

3

 

 

 

DIS

9

8

 

 

 

First

1

-1

-1

2

-1

Next

-1

-1

 

 

 

Step 4:

 

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

 

 

Step 5:

 

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

 

Step 6:

 

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

Create an adjacent table:

1 nT n, m, I; 2 int begin [6], end [6], DIS [6]; 3 int first [6], next [6]; 4 scanf ("% d", & N, & M); 5 // initialize the first array 6 for (I = 1; I <= N; I ++) 7 first [I] =-1; 8 for (I = 1; I <= m; I ++) 9 {10 scanf ("% d ", & begin [I], & End [I], & dis [I]); 11 next [I] = first [begin [I]; 12 first [begin [I] = I; 13}

Traverse all edges of vertex 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 }

 

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.