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
I don't have a JavaScript description but i would generally do it by keeping a queue of unexplored nodes.
Also there is some pseudopod on the Wikipedia page as well as some more explanations HERE
Also a quick Google search turned up a similar algorithm that could be bent to your purpose HERE
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();
}
}
Not completely tested:
var oo = {
board: {
starts: [[0,0],[0,3]],
blocks: [[3,0],[3,3]],
ends: [[2,4]]
},
possibleMoves: [{
board: {
starts: [[0,0],[2,3]],
blocks: [[3,0],[3,3]],
ends: [[2,4]]
},
}],
};
function traverseObject (o) {
for (var prop in o) {
if (typeof o[prop] == "array" || typeof o[prop] == "object") {
traverseObject(o[prop]);
console.log(prop);
} else {
console.log(prop, "=", o[prop]);
}
}
}
traverseObject(oo);