【问题标题】:DFS to get number of items making a pathDFS 获取创建路径的项目数
【发布时间】:2013-04-25 20:22:12
【问题描述】:

我正在尝试获取相互连接的元素的数量,但出现堆栈溢出错误。 问题在于 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;
}

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

【问题讨论】:

    标签: java recursion graph depth-first-search


    【解决方案1】:

    您没有记录您去过的地方。请参阅下面的 cmets。

    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;
    }
    

    【讨论】:

      猜你喜欢
      • 2018-07-24
      • 1970-01-01
      • 2023-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-25
      • 2012-07-16
      相关资源
      最近更新 更多