- for (i = j = 0; i < circuitlen; i++) {
- int xy = nodes[circuit[i]] / DP1;
- if (currstate->grid[xy] == GEM && unvisited[xy] > 1) {
- unvisited[xy]--;
- } else if (currstate->grid[xy] == GEM || i == circuitlen-1) {
- /*
- * circuit[i] collects a gem for the only time, or is
- * the last node in the circuit. Therefore it cannot be
- * removed; so we now want to replace the path from
- * circuit[j] to circuit[i] with a bfs-shortest path.
- */
- int k, dest, ni, ti, thisdist;
+ /*
+ * If there's any gem we didn't end up visiting at all,
+ * give up.
+ */
+ for (i = 0; i < wh; i++) {
+ if (currstate->grid[i] == GEM && unvisited[i] == 0) {
+ err = "Unable to find a solution from this starting point";
+ break;
+ }
+ }
+ if (i < wh)
+ break;
+
+ for (i = j = (dir > 0 ? 0 : circuitlen-1);
+ i < circuitlen && i >= 0;
+ i += dir) {
+ int xy = nodes[circuit[i]] / DP1;
+ if (currstate->grid[xy] == GEM && unvisited[xy] > 1) {
+ unvisited[xy]--;
+ } else if (currstate->grid[xy] == GEM || i == circuitlen-1) {
+ /*
+ * circuit[i] collects a gem for the only time,
+ * or is the last node in the circuit.
+ * Therefore it cannot be removed; so we now
+ * want to replace the path from circuit[j] to
+ * circuit[i] with a bfs-shortest path.
+ */
+ int p, q, k, dest, ni, ti, thisdist;
+
+ /*
+ * Set up the upper and lower bounds of the
+ * reduced section.
+ */
+ p = min(i, j);
+ q = max(i, j);