亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

鄰接矩陣中的BFS

鄰接矩陣中的BFS

C#
米琪卡哇伊 2021-04-29 13:27:16
使用以下代碼,當我調用該bfs方法時,得到的結果是123465247。我應該如何聲明和使用visited變量,以使輸出變為1234657?class Graph{    public int[] graph1VertexList = new int[] {1,2,3,4,5,6,7};    public int[,] graph1=new int[7,7];    public Graph()    {        //for the graph1        graph1[0, 1] = 1;        graph1[0, 2] = 1;        graph1[1, 3] = 1;        graph1[2, 5] = 1;        graph1[3, 4] = 1;        graph1[4, 1] = 1;        graph1[5, 3] = 1;        graph1[5, 6] = 1;    }    public void bfs()    {        Console.Write(graph1VertexList[0]);//print the first value        for(int i = 0; i < graph1VertexList.Length; i++)        {            for(int z = 0; z < graph1VertexList.Length; z++)            {                if (graph1[i, z] == 1)                {                    Console.Write(graph1VertexList[z]);                }            }        }    }}
查看完整描述

1 回答

?
jeck貓

TA貢獻1909條經驗 獲得超7個贊

您應該引入一個布爾數組,以指示某個頂點是否已經被訪問。此外,應檢查數組是否遵循邊并在更新后進行更新。這可以如下進行。


public int[] graph1VertexList = new int[] { 1, 2, 3, 4, 5, 6, 7 };

public int[,] graph1 = new int[7, 7];


public bool[] visited = new bool[7]; // new array, initialized to false


public void bfs()

{

    Console.Write(graph1VertexList[0]);//print the first value

    for (int i = 0; i < graph1VertexList.Length; i++)

    {

        for (int z = 0; z < graph1VertexList.Length; z++)

        {

            if (graph1[i, z] == 1 && !visited[z])   // check for visit

            {

                visited[z] = true;                  // mark as visited

                Console.Write(graph1VertexList[z]);

            }

        }

    }

}


查看完整回答
反對 回復 2021-05-16
  • 1 回答
  • 0 關注
  • 212 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號