猿问

邻接矩阵中的BFS

使用以下代码,当我调用该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]);

                }

            }

        }

    }


}


米琪卡哇伊
浏览 187回答 1
1回答

jeck猫

您应该引入一个布尔数组,以指示某个顶点是否已经被访问。此外,应检查数组是否遵循边并在更新后进行更新。这可以如下进行。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 falsepublic void bfs(){&nbsp; &nbsp; Console.Write(graph1VertexList[0]);//print the first value&nbsp; &nbsp; for (int i = 0; i < graph1VertexList.Length; i++)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; for (int z = 0; z < graph1VertexList.Length; z++)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (graph1[i, z] == 1 && !visited[z])&nbsp; &nbsp;// check for visit&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; visited[z] = true;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // mark as visited&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Console.Write(graph1VertexList[z]);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}
随时随地看视频慕课网APP
我要回答