1{
2 "cells": [
3  {
4   "cell_type": "markdown",
5   "id": "google",
6   "metadata": {},
7   "source": [
8    "##### Copyright 2021 Google LLC."
9   ]
10  },
11  {
12   "cell_type": "markdown",
13   "id": "apache",
14   "metadata": {},
15   "source": [
16    "Licensed under the Apache License, Version 2.0 (the \"License\");\n",
17    "you may not use this file except in compliance with the License.\n",
18    "You may obtain a copy of the License at\n",
19    "\n",
20    "    http://www.apache.org/licenses/LICENSE-2.0\n",
21    "\n",
22    "Unless required by applicable law or agreed to in writing, software\n",
23    "distributed under the License is distributed on an \"AS IS\" BASIS,\n",
24    "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
25    "See the License for the specific language governing permissions and\n",
26    "limitations under the License.\n"
27   ]
28  },
29  {
30   "cell_type": "markdown",
31   "id": "basename",
32   "metadata": {},
33   "source": [
34    "# maze_escape_sat"
35   ]
36  },
37  {
38   "cell_type": "markdown",
39   "id": "link",
40   "metadata": {},
41   "source": [
42    "<table align=\"left\">\n",
43    "<td>\n",
44    "<a href=\"https://colab.research.google.com/github/google/or-tools/blob/master/examples/notebook/examples/maze_escape_sat.ipynb\"><img src=\"https://raw.githubusercontent.com/google/or-tools/master/tools/colab_32px.png\"/>Run in Google Colab</a>\n",
45    "</td>\n",
46    "<td>\n",
47    "<a href=\"https://github.com/google/or-tools/blob/master/examples/python/maze_escape_sat.py\"><img src=\"https://raw.githubusercontent.com/google/or-tools/master/tools/github_32px.png\"/>View source on GitHub</a>\n",
48    "</td>\n",
49    "</table>"
50   ]
51  },
52  {
53   "cell_type": "markdown",
54   "id": "doc",
55   "metadata": {},
56   "source": [
57    "First, you must install [ortools](https://pypi.org/project/ortools/) package in this colab."
58   ]
59  },
60  {
61   "cell_type": "code",
62   "execution_count": null,
63   "id": "install",
64   "metadata": {},
65   "outputs": [],
66   "source": [
67    "!pip install ortools"
68   ]
69  },
70  {
71   "cell_type": "code",
72   "execution_count": null,
73   "id": "code",
74   "metadata": {},
75   "outputs": [],
76   "source": [
77    "#!/usr/bin/env python3\n",
78    "# Copyright 2010-2021 Google LLC\n",
79    "# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
80    "# you may not use this file except in compliance with the License.\n",
81    "# You may obtain a copy of the License at\n",
82    "#\n",
83    "#     http://www.apache.org/licenses/LICENSE-2.0\n",
84    "#\n",
85    "# Unless required by applicable law or agreed to in writing, software\n",
86    "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
87    "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
88    "# See the License for the specific language governing permissions and\n",
89    "# limitations under the License.\n",
90    "\"\"\"Excape the maze while collecting treasures in order.\n",
91    "\n",
92    "The path must begin at the 'start' position, finish at the 'end' position,\n",
93    "visit all boxes in order, and walk on each block in a 4x4x4 map exactly once.\n",
94    "\n",
95    "Admissible moves are one step in one of the 6 directions:\n",
96    "  x+, x-, y+, y-, z+(up), z-(down)\n",
97    "\"\"\"\n",
98    "from typing import Sequence\n",
99    "\n",
100    "from absl import app\n",
101    "from absl import flags\n",
102    "from google.protobuf import text_format\n",
103    "from ortools.sat.python import cp_model\n",
104    "\n",
105    "FLAGS = flags.FLAGS\n",
106    "\n",
107    "flags.DEFINE_string('output_proto', '',\n",
108    "                    'Output file to write the cp_model proto to.')\n",
109    "flags.DEFINE_string('params', 'num_search_workers:8,log_search_progress:true',\n",
110    "                    'Sat solver parameters.')\n",
111    "\n",
112    "\n",
113    "def add_neighbor(size, x, y, z, dx, dy, dz, model, index_map, position_to_rank,\n",
114    "                 arcs):\n",
115    "    \"\"\"Checks if the neighbor is valid, and adds it to the model.\"\"\"\n",
116    "    if (x + dx < 0 or x + dx >= size or y + dy < 0 or y + dy >= size or\n",
117    "            z + dz < 0 or z + dz >= size):\n",
118    "        return\n",
119    "    before_index = index_map[(x, y, z)]\n",
120    "    before_rank = position_to_rank[(x, y, z)]\n",
121    "    after_index = index_map[(x + dx, y + dy, z + dz)]\n",
122    "    after_rank = position_to_rank[(x + dx, y + dy, z + dz)]\n",
123    "    move_literal = model.NewBoolVar('')\n",
124    "    model.Add(after_rank == before_rank + 1).OnlyEnforceIf(move_literal)\n",
125    "    arcs.append((before_index, after_index, move_literal))\n",
126    "\n",
127    "\n",
128    "def escape_the_maze(params, output_proto):\n",
129    "    \"\"\"Escapes the maze.\"\"\"\n",
130    "    size = 4\n",
131    "    boxes = [(0, 1, 0), (2, 0, 1), (1, 3, 1), (3, 1, 3)]\n",
132    "    start = (3, 3, 0)\n",
133    "    end = (1, 0, 0)\n",
134    "\n",
135    "    # Builds a map between each position in the grid and a unique integer between\n",
136    "    # 0 and size^3 - 1.\n",
137    "    index_map = {}\n",
138    "    reverse_map = []\n",
139    "    counter = 0\n",
140    "    for x in range(size):\n",
141    "        for y in range(size):\n",
142    "            for z in range(size):\n",
143    "                index_map[(x, y, z)] = counter\n",
144    "                reverse_map.append((x, y, z))\n",
145    "                counter += 1\n",
146    "\n",
147    "    # Starts building the model.\n",
148    "    model = cp_model.CpModel()\n",
149    "    position_to_rank = {}\n",
150    "\n",
151    "    for coord in reverse_map:\n",
152    "        position_to_rank[coord] = model.NewIntVar(0, counter - 1,\n",
153    "                                                  f'rank_{coord}')\n",
154    "\n",
155    "    # Path constraints.\n",
156    "    model.Add(position_to_rank[start] == 0)\n",
157    "    model.Add(position_to_rank[end] == counter - 1)\n",
158    "    for i in range(len(boxes) - 1):\n",
159    "        model.Add(position_to_rank[boxes[i]] < position_to_rank[boxes[i + 1]])\n",
160    "\n",
161    "    # Circuit constraint: visit all blocks exactly once, and maintains the rank\n",
162    "    # of each block.\n",
163    "    arcs = []\n",
164    "    for x in range(size):\n",
165    "        for y in range(size):\n",
166    "            for z in range(size):\n",
167    "                add_neighbor(size, x, y, z, -1, 0, 0, model, index_map,\n",
168    "                             position_to_rank, arcs)\n",
169    "                add_neighbor(size, x, y, z, 1, 0, 0, model, index_map,\n",
170    "                             position_to_rank, arcs)\n",
171    "                add_neighbor(size, x, y, z, 0, -1, 0, model, index_map,\n",
172    "                             position_to_rank, arcs)\n",
173    "                add_neighbor(size, x, y, z, 0, 1, 0, model, index_map,\n",
174    "                             position_to_rank, arcs)\n",
175    "                add_neighbor(size, x, y, z, 0, 0, -1, model, index_map,\n",
176    "                             position_to_rank, arcs)\n",
177    "                add_neighbor(size, x, y, z, 0, 0, 1, model, index_map,\n",
178    "                             position_to_rank, arcs)\n",
179    "\n",
180    "    # Closes the loop as the constraint expects a circuit, not a path.\n",
181    "    arcs.append((index_map[end], index_map[start], True))\n",
182    "\n",
183    "    # Adds the circuit (hamiltonian path) constraint.\n",
184    "    model.AddCircuit(arcs)\n",
185    "\n",
186    "    # Exports the model if required.\n",
187    "    if output_proto:\n",
188    "        model.ExportToFile(output_proto)\n",
189    "\n",
190    "    # Solve model.\n",
191    "    solver = cp_model.CpSolver()\n",
192    "    if params:\n",
193    "        text_format.Parse(params, solver.parameters)\n",
194    "    solver.parameters.log_search_progress = True\n",
195    "    result = solver.Solve(model)\n",
196    "\n",
197    "    # Prints solution.\n",
198    "    if result == cp_model.OPTIMAL:\n",
199    "        path = [''] * counter\n",
200    "        for x in range(size):\n",
201    "            for y in range(size):\n",
202    "                for z in range(size):\n",
203    "                    position = (x, y, z)\n",
204    "                    rank = solver.Value(position_to_rank[position])\n",
205    "                    msg = f'({x}, {y}, {z})'\n",
206    "                    if position == start:\n",
207    "                        msg += ' [start]'\n",
208    "                    elif position == end:\n",
209    "                        msg += ' [end]'\n",
210    "                    else:\n",
211    "                        for b in range(len(boxes)):\n",
212    "                            if position == boxes[b]:\n",
213    "                                msg += f' [boxes {b}]'\n",
214    "                    path[rank] = msg\n",
215    "        print(path)\n",
216    "\n",
217    "\n",
218    "if len(argv) > 1:\n",
219    "    raise app.UsageError('Too many command-line arguments.')\n",
220    "escape_the_maze(FLAGS.params, FLAGS.output_proto)\n",
221    "\n"
222   ]
223  }
224 ],
225 "metadata": {},
226 "nbformat": 4,
227 "nbformat_minor": 5
228}
229