For each adjacent position, look at each adjacent position except the previous position.
var move = (function () { var adj = { 1: [25, 21, 2], 2: [ 1, 3] , 3: [ 2, 4], 4: [ 3, 5] , 5: [ 4, 6], 6: [ 5, 19, 7], 7: [ 6, 8] , 8: [ 7, 9], 9: [10, 8] , 10: [11, 9], 11: [10, 12] , 12: [11, 13] , 13: [12, 14], 14: [13, 15, 22], 15: [14, 16], 16: [15, 17] , 17: [16, 20, 18], 18: [17, 19], 19: [18, 6] , 20: [17, 21], 21: [ 1, 20] , 22: [14, 23] , 23: [22, 24], 24: [23, 25] , 25: [24, 1] }; function move(current, steps_remaining, prev) { var arr = [], i = adj[current].length; prev || (prev = 0); // if there wasn't a previous position, choose impossible if (steps_remaining) { // if we can still move while (i--) // for each adj tile if (adj[current][i] !== prev) // that isn't where we just came from arr = arr.concat( // concat together move(adj[current][i], steps_remaining - 1, current) ); // recursion from adjacent tiles return arr; // return recursion } // else return current tile return [current]; } return move; }());
Then
move(11, 4); // [22, 15, 7]
Bonus added: you do not need additional global variables