【问题标题】:ArrayIndexOutOfBoundsException in DFSDFS 中的 ArrayIndexOutOfBoundsException
【发布时间】:2023-04-06 11:27:01
【问题描述】:

错误行是 69,33,51。错误是数组索引超出范围

以下是深度优先搜索算法的java代码。

在 69,33,51 显示数组索引超出范围异常..

public class dfs1 {

    Stack<Integer> st;
    int vFirst;
    int[][] matrix;
    int[] isVisited = new int[3];
    public static void main(String args[])
    {
        Scanner input=new Scanner(System.in);
        System.out.println("enter the no of vertices");
        int size=input.nextInt();
        int[][] matrix=new int[size][size];
        System.out.println("enter the values for matrix");

        for(int row=0;row<size;row++)
        {
            for(int col=0;col<size;col++){
                matrix[row][col]=input.nextInt();
            }
        }
        System.out.println("the adjacency matrix is ");
        for(int row=0;row<size;row++)
        {
            for(int col=0;col<size;col++){
                System.out.println(matrix[row][col]);
            }
        }
        System.out.println("enter the start vertex ");
        int start=input.nextInt();
        new dfs1(matrix,size,start);



    }


    public dfs1(int[][] matrix,int size,int start)
    {
        this.matrix = matrix;
        st = new Stack<Integer>();

        int[] node=new int[size];
        for(int i=0;i<size;i++)
        {
            node[i]=i;
        }
        int firstNode = start;
        depthFirst(firstNode,size);
    }
    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((matrix[v][i] == 1) && (isVisited[i] == 0))
            {
                st.push(v);
                isVisited[i]=1;
                System.out.print(" " + (i+1));
                v = i;
            }
        }
    }
    }
}

【问题讨论】:

  • 行号并没有真正帮助我们。您能告诉我们导致此问题的特定代码行吗?
  • 您能否澄清一下您的矩阵的大小,以及您为起始顶点输入的数字?另外,我强烈建议您使用调试器逐步完成此操作 - 我相信如果您这样做,您会很快发现您的问题。最后,您确实需要告诉我们您的问题出现在哪一行 - 您的列表中没有行号,因此该数字根本没有帮助。

标签: java arrays exception depth-first-search


【解决方案1】:

你有

int[] isVisited = new int[3];

但实际上这个数组至少应该是size long

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-01
    • 2014-02-01
    • 2013-08-25
    • 1970-01-01
    • 1970-01-01
    • 2014-09-22
    • 1970-01-01
    相关资源
    最近更新 更多