【问题标题】:Depth First Traversal and Adj Matrix深度优先遍历和调整矩阵
【发布时间】:2011-11-11 01:26:26
【问题描述】:

我正在尝试进行深度优先遍历。我不知道我是否接近。现在它正在打印 1 3 4 5。它应该打印 1 2 4 7 3 5 6。感谢任何帮助或建议。谢谢。 :)

类:

 public class myGraphs {
     Stack<Integer> st;
     int vFirst;

     int[][] adjMatrix;
     int[] isVisited = new int[7];


     public myGraphs(int[][] Matrix) {
         this.adjMatrix = Matrix;
         st = new Stack<Integer>();
         int i;
         int[] node = {1, 2, 3, 4, 5, 6, 7};
         int firstNode = node[0];

         for (i = 1; i < node.length - 1; i++) {
             depthFirst(firstNode, node[i]);
         }
    }

    public void depthFirst(int vFirst, int n) {
        int v, i;

        st.push(vFirst);

        while (!st.isEmpty()) {
            v = st.pop();
            if (isVisited[v]==0) {
                System.out.print("\n"+v);
                isVisited[v]=1;
            }

            for ( i=1;i<=n;i++) {
                if ((adjMatrix[v][i] == 1) && (isVisited[i] == 0)) {
                    st.push(v);
                    isVisited[i]=1;
                    System.out.print(" " + i);
                    v = i;
                }
            }
        }
    }

    //
    public static void main(String[] args) {     
        // 1  2  3  4  5  6  7
        int[][] adjMatrix = { {0, 1, 1, 0, 0, 0, 0},
                              {1, 0, 0, 1, 1, 1, 0},
                              {1, 0, 0, 0, 0, 0, 1},
                              {0, 1, 0, 0, 0, 0, 1},
                              {0, 1, 0, 0, 0, 0, 1},
                              {0, 1, 0, 0, 0, 0 ,0},
                              {0, 0, 1, 1, 1, 0, 0}  };

       new myGraphs(adjMatrix);
     }
}

【问题讨论】:

  • 深度优先搜索什么?
  • 这是对图的深度搜索。
  • 但是你在搜索什么?
  • 你必须在这里定义“深度”。根据我的阅读,我希望 [1 2 4 7 3 5 6],因为 7 可以转到 3 和 5。
  • OP 的意思是说深度优先遍历

标签: java graph


【解决方案1】:

如果您正在查看深度优先遍历,那么以下是您应该进行的代码更改

1) 首先将你的节点数组声明为int[] node = {0, 1, 2, 3, 4, 5, 6}。应该这样做以避免数组索引开始(即 0 )和您的节点开始编号(即 1)。所以现在我们假设你的节点 1 的新名称是 0,节点 2 是 1......并且节点 7 是 6。

2) 而不是做

for (i = 1; i < node.length-1; i++){
     depthFirst(firstNode, node[i]);
 } 

在 myGraphs 中: depthFirst(firstNode, 7);

3)在depthFirst而不是for ( i=1;i&lt;=n;i++)使用for ( i=0;i&lt;n;i++)在函数depthFirst中执行System.out.println时将数字加一,因为0代表节点1,1代表节点2等等。

以下是我修改的完整功能代码:

import java.util.Stack;


public class DFS {

    Stack<Integer> st;
      int vFirst;

      int[][] adjMatrix;
      int[] isVisited = new int[7];

    /**
     * @param args
     */
    public static void main(String[] args) {
        int[][] adjMatrix = { {0, 1, 1, 0, 0, 0, 0},
                {1, 0, 0, 1, 1, 1, 0},
                {1, 0, 0, 0, 0, 0, 1},
                {0, 1, 0, 0, 0, 0, 1},
                {0, 1, 0, 0, 0, 0, 1},
                {0, 1, 0, 0, 0, 0 ,0},
                {0, 0, 1, 1, 1, 0, 0}  };


      new DFS(adjMatrix);

    }

    public DFS(int[][] Matrix) {

         this.adjMatrix = Matrix;
         st = new Stack<Integer>();
         int i;
         int[] node = {0, 1, 2, 3, 4, 5, 6};
         int firstNode = node[0];
         depthFirst(firstNode, 7);



          }

          public void depthFirst(int vFirst,int n)
          {
          int v,i;

          st.push(vFirst);

          while(!st.isEmpty())
          {
              v = st.pop();
              if(isVisited[v]==0)
              {
                  System.out.print("\n"+(v+1));
                  isVisited[v]=1;
              }
              for ( i=0;i<n;i++)
              {
                  if((adjMatrix[v][i] == 1) && (isVisited[i] == 0))
                  {
                      st.push(v);
                      isVisited[i]=1;
                      System.out.print(" " + (i+1));
                      v = i;
                  }
              }
          }
}}

【讨论】:

  • 当我将 int[] 节点更改为 0-6 时,它确实有效。除了 firstnode 我真的不需要 int[] 节点。感谢您的帮助。
  • Saurabh,我刚刚测试了你的代码,它打印的是 1、2、4、7、5、6、3 而不是 1、2、4、7、3、5、6。你能请测试并确认?
【解决方案2】:

C# 中的工作/测试解决方案,如果有人正在寻找它。

using System;
using System.Collections.Generic;

namespace GraphAdjMatrixDemo
{
    public class Program
    {
        public static void Main(string[] args)
        {
            // 0  1  2  3  4  5  6
            int[,] matrix = {     {0, 1, 1, 0, 0, 0, 0},
                                  {1, 0, 0, 1, 1, 1, 0},
                                  {1, 0, 0, 0, 0, 0, 1},
                                  {0, 1, 0, 0, 0, 0, 1},
                                  {0, 1, 0, 0, 0, 0, 1},
                                  {0, 1, 0, 0, 0, 0 ,0},
                                  {0, 0, 1, 1, 1, 0, 0}  };

            bool[] visitMatrix = new bool[matrix.GetLength(0)];
            Program ghDemo = new Program();

            for (int lpRCnt = 0; lpRCnt < matrix.GetLength(0); lpRCnt++)
            {
                for (int lpCCnt = 0; lpCCnt < matrix.GetLength(1); lpCCnt++)
                {
                    Console.Write(string.Format(" {0}  ", matrix[lpRCnt, lpCCnt]));
                }
                Console.WriteLine();
            }

            Console.Write("\nDFS Recursive : ");
            ghDemo.DftRecursive(matrix, visitMatrix, 0);
            Console.Write("\nDFS Iterative : ");
            ghDemo.DftIterative(matrix, 0);

            Console.Read();
        }

        //====================================================================================================================================

        public void DftRecursive(int[,] srcMatrix, bool[] visitMatrix, int vertex)
        {
            visitMatrix[vertex] = true;
            Console.Write(vertex + 1 + "  ");

            for (int neighbour = 0; neighbour < srcMatrix.GetLength(0); neighbour++)
            {
                if (visitMatrix[neighbour] == false && srcMatrix[vertex, neighbour] == 1)
                {
                    DftRecursive(srcMatrix, visitMatrix, neighbour);
                }
            }
        }

        public void DftIterative(int[,] srcMatrix, int srcVertex)
        {
            bool[] visited = new bool[srcMatrix.GetLength(0)];

            Stack<int> vertexStack = new Stack<int>();
            vertexStack.Push(srcVertex);

            while (vertexStack.Count > 0)
            {
                int vertex = vertexStack.Pop();

                if (visited[vertex] == true)
                    continue;

                Console.Write(vertex + 1 + "  ");
                visited[vertex] = true;

                for (int neighbour = 0; neighbour < srcMatrix.GetLength(0); neighbour++) 
                //for (int neighbour = srcMatrix.GetLength(0) - 1; neighbour >= 0; neighbour--)// To make same as recursive
                {
                    if (srcMatrix[vertex, neighbour] == 1 && visited[neighbour] == false)
                    {
                        vertexStack.Push(neighbour);
                    }
                }
            }
        }
    }
}

为了使迭代的显示顺序与递归相同,我们需要将邻居以相反的顺序推入堆栈。从 Amit 回答 here

中得到这个逻辑

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-10
    • 2019-01-08
    • 1970-01-01
    相关资源
    最近更新 更多