二維碼
企資網

掃一掃關注

當前位置: 首頁 » 企業資訊 » 熱點 » 正文

2021_12_04_公交路線。給你一個數組_

放大字體  縮小字體 發布日期:2021-12-07 10:03:30    作者:付煜萱    瀏覽次數:49
導讀

2021-12-04:公交路線。給你一個數組 routes ,表示一系列公交線路,其中每個 routes[i] 表示一條公交線路,第 i 輛公交車將會在上面循環行駛。例如,路線 routes[0] = [1, 5, 7] 表示第 0 輛公交車會一直按序列 1 -

2021-12-04:公交路線。給你一個數組 routes ,表示一系列公交線路,其中每個 routes[i] 表示一條公交線路,第 i 輛公交車將會在上面循環行駛。

例如,路線 routes[0] = [1, 5, 7] 表示第 0 輛公交車會一直按序列 1 -> 5 -> 7 -> 1 -> 5 -> 7 -> 1 -> ... 這樣得車站路線行駛。

現在從 source 車站出發(初始時不在公交車上),要前往 target 車站。 期間僅可乘坐公交車。

求出 蕞少乘坐得公交車數量 。如果不可能到達終點車站,返回 -1 。

來自力扣815。

來自三七互娛。

答案2021-12-04:

以公交線做寬度優先遍歷。

代碼用golang編寫。代碼如下:

package mainimport "fmt"func main() { routes := [][]int{{1, 2, 7}, {3, 6, 7}} source := 1 target := 6 ret := numBusesToDestination(routes, source, target) fmt.Println(ret)}func numBusesToDestination(routes [][]int, source, target int) int { if source == target { return 0 } n := len(routes) // key : 車站 // value : list -> 該車站擁有哪些線路! map0 := make(map[int][]int) for i := 0; i < n; i++ { for j := 0; j < len(routes[i]); j++ { if _, ok := map0[routes[i][j]]; !ok { map0[routes[i][j]] = make([]int, 0) } map0[routes[i][j]] = append(map0[routes[i][j]], i) } } queue := make([]int, 0) set := make([]bool, n) for _, route := range map0[source] { queue = append(queue, route) set[route] = true } len0 := 1 for len(queue) > 0 { nextLevel := make([]int, 0) for _, route := range queue { bus := routes[route] for _, station := range bus { if station == target { return len0 } for _, nextRoute := range map0[station] { if !set[nextRoute] { nextLevel = append(nextLevel, nextRoute) set[nextRoute] = true } } } } queue = nextLevel len0++ } return -1}

執行結果如下:

***

[左神java代碼](gitee/moonfdd/coding-for-great-offer/blob/main/src/class36/Code12_BusRoutes.java)

 
(文/付煜萱)
免責聲明
本文僅代表作發布者:付煜萱個人觀點,本站未對其內容進行核實,請讀者僅做參考,如若文中涉及有違公德、觸犯法律的內容,一經發現,立即刪除,需自行承擔相應責任。涉及到版權或其他問題,請及時聯系我們刪除處理郵件:weilaitui@qq.com。
 

Copyright ? 2016 - 2025 - 企資網 48903.COM All Rights Reserved 粵公網安備 44030702000589號

粵ICP備16078936號

微信

關注
微信

微信二維碼

WAP二維碼

客服

聯系
客服

聯系客服:

在線QQ: 303377504

客服電話: 020-82301567

E_mail郵箱: weilaitui@qq.com

微信公眾號: weishitui

客服001 客服002 客服003

工作時間:

周一至周五: 09:00 - 18:00

反饋

用戶
反饋

日韩欧美国产免费看清风阁