DFS中的ArrayIndexOutOfBoundsException

时间:2014-11-02 06:11:10

标签: java arrays exception depth-first-search

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

以下是深度优先搜索alogorithm的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;
            }
        }
    }
    }
}

1 个答案:

答案 0 :(得分:1)

你有

int[] isVisited = new int[3];

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