- memcpy(scratch->sparegrid, grid, wh * sizeof(*grid));
- fill(w, h, scratch->sparegrid, x0, y0, move, scratch->queue[0]);
+ memcpy(tmpgrid, grid, wh * sizeof(*grid));
+ fill(w, h, tmpgrid, x0, y0, move, scratch->queue[0]);
+ if (completed(w, h, tmpgrid)) {
+ /*
+ * A move that wins is immediately the best, so stop
+ * searching. Record what depth of recursion that happened
+ * at, so that higher levels will choose a move that gets
+ * to a winning position sooner.
+ */
+ *rbestdist = -1;
+ *rbestnumber = depth;
+ *rbestcontrol = wh;
+ return move;
+ }
+ if (depth < RECURSION_DEPTH-1) {
+ choosemove_recurse(w, h, tmpgrid, x0, y0, maxmove, scratch,
+ depth+1, &dist, &number, &control);
+ } else {