DFS获取制作路径的项目数

时间:2013-04-25 20:22:12

标签: java recursion graph depth-first-search

我正在尝试获取彼此连接的元素数量,但我有堆栈溢出错误。 问题在于DFS算法。

public int DFS(int x, int y){
    int num = 1;
    Point p = new Point(x, y); //fix
    int color = this.getColor(p);
    Checkers h = new Checkers(color,p);

    h.setVisited();
    for(int dx=-1; dx<=1; dx++){
        for(int dy=-1; dy<=1; dy++){
            Point u = new Point(x+dx, y+dy);
            if (this.getColor(u)==color){ 
                num = num + DFS(x+dx, y+dy);
            }
        }
    }
    return num;
}

我想返回连接在一起的元素数量。

1 个答案:

答案 0 :(得分:0)

你没有跟踪你去过的地方。见下面的评论。

public int DFS(int x, int y){
    int num = 1;
    Point p = new Point(x, y); //fix
    int color = this.getColor(p);
    Checkers h = new Checkers(color,p);

    // this is good, but you've creating the object in the DFS, meaning when 
    // you revisit it, you don't know you've been here. You need a 
    // class variable representing each part in the grid.
    h.setVisited();

    for(int dx=-1; dx<=1; dx++){
        for(int dy=-1; dy<=1; dy++){
            Point u = new Point(x+dx, y+dy);

            // need to test h.isVisited();
            if (this.getColor(u)==color){ 
                num = num + DFS(x+dx, y+dy);
            }
        }
    }
    return num;
}