PAT:05-1. List Components (25),Go語言解答

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

題目大概意思:給定一個有N個頂點和E個邊的無向圖,請分別用DFS和BFS遍曆無向圖。假定頂點編號為0到N-1,在遍曆的時候總是從最小編號的頂點出發,在訪問相鄰結點的時候,按升序的方式訪問。

 

For a given undirected graph with N vertices and E edges, pleaselist all the connected components by both DFS and BFS. Assume thatall the vertices are numbered from 0 to N-1. While searching,assume that we always start from the vertex with the smallestindex, and visit its adjacent vertices in ascending order of theirindices.

Input Specification:

Each input file contains one test case. For each case, the firstline gives two integers N (0

Output Specification:

For each test case, print in each line a connected component inthe format "{ v1 v2 ... vk }". First print the result obtained byDFS, then by BFS.

Sample Input:

8 60 70 12 04 12 43 5

Sample Output:

{ 0 1 4 2 7 }{ 3 5 }{ 6 }{ 0 1 2 7 4 }{ 3 5 }{ 6 }
 001 packagemain
002 
003 import (
004    "fmt"
005    "container/heap"
006    "container/list"
007 )
008 var visited = make([]bool, 10)//題目給出頂點數不會超過10,至少為1
009 var G =make([]IntHeap,10)
010 
011 func main(){
012    varNumOfV,NumOfEint
013    //接受頂點數和邊數
014    _, err:=fmt.Scanf("%d %d\n",&NumOfV,&NumOfE)
015    iferr !=nil {
016       fmt.Println("error",err)
017    }
018    fori :=0; i<</SPAN>NumOfE;i++{//給頂點列表裝入資料
019       var v1,v2int
020       _, err =fmt.Scanf("%d%d\n",&v1,&v2)
021       if err != nil {
022          fmt.Println("error",err)
023       }
024       heap.Push(&G[v1],v2)
025       heap.Push(&G[v2],v1)
026    }
027    //************************************
028    //開始遍曆
029    //*************************************
030    fori:= 0; i<</SPAN>NumOfV;i++ {
031       if !visited[i]{
032          fmt.Print("{ ")
033          dfs(i);
034          fmt.Print("}\n")
035       }
036    }
037    //重設visited數組
038    fori :=range visited {
039       visited[i]=false
040    }
041    fori :=0; i<</SPAN>NumOfV;i++ {
042       if !visited[i]{
043          fmt.Print("{ ")
044          bfs(i)
045          fmt.Print("}\n")
046       }
047    }
048 }
049 //深度優先搜尋(Depth First Search, DFS):
050 //訪問下一個可見的未被訪問的元素,
051 //如果所有的可見元素都被訪問過,則返回上一個元素
052 func dfs(vint) (){
053    visited[v]=true
054    fmt.Printf("%d",v)
055    for_,neibor:= range G[v]{//遍曆相鄰節點
056       if !visited[neibor]{
057          dfs(neibor)
058       }
059    }
060 }
061 //廣度優先搜尋(Breadth First Search, BFS):
062 //類似層序遍曆的思想,使用隊列來操作,先把1放入隊列,出隊時,將1的所有鄰接點放入隊列
063 func bfs(vint) (){
064    varls =list.New()
065    visited[v]=true
066    fmt.Printf("%d",v)
067    ls.PushBack(v)
068    forls.Len()!= 0 {
069       ele := ls.Front()
070       ls.Remove(ele)
071       theV :=ele.Value.(int)//theV.Value是介面類型,所以需要斷言
072       
073       for _,neibor:= range G[theV]{//遍曆相鄰節點
074          if !visited[neibor] {
075              visited[neibor]= true
076              fmt.Printf("%d",neibor)
077              ls.PushBack(neibor)
078          }
079       }
080    }
081 }
082 
083 //heap操作,最小堆
084 type IntHeap []int
085 
086 func (hIntHeap)Len()int         { returnlen(h)}
087 func (hIntHeap)Less(i,jint) bool { return h[i]<</SPAN>h[j] }
088 func (hIntHeap)Swap(i,jint)    { h[i], h[j]=h[j], h[i]}
089 
090 func (h*IntHeap)Push(xinterface{}){
091    // Push andPop use pointer receivers because they modify the slice'slength,
092    // not justits contents.
093    *h =append(*h,x.(int))
094 }
095 
096 func (h*IntHeap)Pop() interface{} {
097    old:= *h
098    n:= len(old)
099    x:= old[n-1]
100    *h =old[0: n-1]
101    returnx
102 }

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

相關文章

聯繫我們

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