・実際の結果
0と5……System.IndexOutOfRangeException: インデックスが配列の境界外です。と表示される(337行目)
1と5……Process is terminated due to StackOverflowException.と表示される。
2と5……2,4,1と表示後、Process is terminated due to StackOverflowException.と表示される。
3と5……3,1と表示後、Process is terminated due to StackOverflowException.と表示される。
5と0……System.IndexOutOfRangeException: インデックスが配列の境界外です。と表示される(337行目)
5と1……System.IndexOutOfRangeException: インデックスが配列の境界外です。と表示される(337行目)
5と2……System.IndexOutOfRangeException: インデックスが配列の境界外です。と表示される(337行目)
5と3……System.IndexOutOfRangeException: インデックスが配列の境界外です。と表示される(337行目)
0と5……0,1と表示後、Process is terminated due to StackOverflowException.と表示される。
1と5……1,2と表示後。Process is terminated due to StackOverflowException.と表示される。
2と5……2,4,1、1,2と表示後、Process is terminated due to StackOverflowException.と表示される。
3と5……3,1、1,2と表示後、Process is terminated due to StackOverflowException.と表示される。
3と0……while内無限ループ
4と0……while内無限ループ
5と0……while内無限ループ
5と1……while内無限ループ
5と2……while内無限ループ
5と3……while内無限ループ
残りの組み合わせは問題ありませんでした。
また「System.IndexOutOfRangeException: インデックスが配列の境界外です。」の表示は出ませんでした。
1package main
23import(4"bufio"5"fmt"6"os"7)89var stations =[]string{10"駅0",11"駅1",12"駅2",13"駅3",14"駅4",15"駅5",16}1718var lines =[][]int{19{0,1,2},20{3,1,4,2},21{4,5},22}2324var nextStations =[][]int{}2526var results =[][]int{}2728funcmain(){29// 準備: 隣接駅のリストを作っておく30for s :=0; s <len(stations); s++{31 nextStations =append(nextStations,listNextStations(s))32}3334// 出発駅と到着駅を入力35 scanner := bufio.NewScanner(os.Stdin)3637 fmt.Print("出発駅……")38 scanner.Scan()39 start := scanner.Text()40 fmt.Print("到着駅……")41 scanner.Scan()42 goal := scanner.Text()4344 s :=-145 g :=-146for i, v :=range stations {47switch v {48case start:49 s = i
50case goal:51 g = i
52}53if0<= s &&0<= g {54break55}56}5758// 結果を得る59findResults(s, g,[]int{})6061 fmt.Println(len(results)," routes")62 fmt.Println(results)63}6465// 駅 s に隣接するすべての駅を列挙する66funclistNextStations(s int)[]int{67var next =[]int{}6869for_, line :=range lines {70for i, station :=range line {71if s == station {72if0< i {73 next =append(next, line[i-1])74}75if i <len(line)-1{76 next =append(next, line[i+1])77}78}79}80}8182return next
83}8485// 駅 s から最終目的の駅 g までの経路を探索し、86// 見つかったものを配列 results に加える。87// visited はこれまでに通ってきた駅の配列 (s が出発駅なら空)。88funcfindResults(s, g int, visited []int){89// 経路を一駅進める90 visited =append(visited, s)9192// 隣接する駅をすべて調べる93for_, n :=range nextStations[s]{94// ゴールなら経路を記録して、その先はもう調べない95if n == g {96 result :=make([]int,len(visited)+1)97copy(result,append(visited, n))98 results =append(results, result)99continue100}101102// すでに通った駅ならもう調べない103var passed bool104for_, v :=range visited {105if n == v {106 passed =true107break108}109}110if passed {111continue112}113114// 上記のいずれでもなければ、次の駅に進んで探索を続行115findResults(n, g, visited)116}117// すべての隣接駅を調べ終わったら (再帰) 関数の呼び出しから戻る118119// 経路を一駅戻す120 visited = visited[:len(visited)-1]121}