Breadth first traversal of object

前端 未结 3 1452
南旧
南旧 2021-02-02 04:47

I am making a program that solves a puzzle game, and it finds all the possible moves on a board and puts all the possible resulting boards in an object. Then it finds all the po

3条回答
  •  青春惊慌失措
    2021-02-02 05:06

    Recursion.

    function traverse(state) {
        handle(state.board);
        if (state.possibleMoves) {
            $.each(state.possibleMoves, function(i, possibleMove) {
                 traverse(possibleMove);
            });
        }
    }
    

    EDIT: For a breadth-first search, try something like this. It doesn't use recursion, but instead iterates over a growing queue.

    function traverse(state) {
        var queue = [],
            next = state;
        while (next) {
            if (next.possibleMoves) {
                $.each(next.possibleMoves, function(i, possibleMove) {
                    queue.push(possibleMove);
                });
            }
            next = queue.shift();
        }
    }
    

提交回复
热议问题