All possible paths

≯℡__Kan透↙ 提交于 2019-12-11 00:58:33

问题


I am currently working on an AI for playing the game Dots (link). The objective is to remove as many dots as possible by connecting similarly colored dots with a line. I've gone through the board and grouped each set of neighboring dots with the same color. The groups all currently share the same highlight color (black). So, for example, the four red dots in the top left form a single group, as do the three yellow dots on the top right.

I need to calculate every possible path through one of these groups. Can anyone think of a good algorithm? How could I avoid creating duplicate paths?

I've heard that a slightly modified DFS would be good in this situation. However, the paths are allowed to cross at nodes, but cannot reuse edges. How can I modify DFS accordingly?


回答1:


Here's some pseudo code to get you started. It's how I would probably do it. Using edges instead of nodes solves the situation with crossing paths neatly, but retrieving edges is more difficult than nodes. You need to map the edge indexes to the node indexes.

You will get every path two times, since a path can be traversed from two directions. If the dot groups grow large, consider pruning the least interesting paths. The memory requirement grows exponentially as 4^n where n is the number of dots in the group. I can't think of a good way to add incomplete paths without allowing for duplicates, but perhaps you're not interested in paths ending early?

private LinkedList<Edge> recurse(LinkedList<Edge> path) {
    Edge last = path.getLast();
    Edge right = <get Edge to the right of last>;
    Edge bottom = <get Edge below last>;
    Edge left = <get Edge to the left of last>;
    Edge top = <get Edge above last>;
    if( right && !path.contains(right) ) {
        LinkedList<Edge> ps = path.clone();  // NOTE: check if the built-in clone() function does a shallow copy
        ps.addLast( right );
        paths.add( recurse(ps) );
    }
    if( bottom && !path.contains(bottom) ) {
        ...
    }
    if( left && !path.contains(left) ) {
        ...
    }
    if( top && !path.contains(top) ) {
        ...
    }
    return path;
}


来源:https://stackoverflow.com/questions/20888629/all-possible-paths

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!