{"id":1768,"date":"2018-02-06T22:02:55","date_gmt":"2018-02-07T06:02:55","guid":{"rendered":"http:\/\/zxi.mytechroad.com\/blog\/?p=1768"},"modified":"2018-02-06T23:36:10","modified_gmt":"2018-02-07T07:36:10","slug":"leetcode-773-sliding-puzzle","status":"publish","type":"post","link":"https:\/\/zxi.mytechroad.com\/blog\/searching\/leetcode-773-sliding-puzzle\/","title":{"rendered":"\u82b1\u82b1\u9171 LeetCode 773. Sliding Puzzle"},"content":{"rendered":"<p><iframe loading=\"lazy\" title=\"\u82b1\u82b1\u9171 LeetCode 773. Sliding Puzzle - \u5237\u9898\u627e\u5de5\u4f5c EP167\" width=\"500\" height=\"375\" src=\"https:\/\/www.youtube.com\/embed\/ABSjW0p3wsM?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" referrerpolicy=\"strict-origin-when-cross-origin\" allowfullscreen><\/iframe><\/p>\n<p>\u9898\u76ee\u5927\u610f\uff1a\u7ed9\u4f60\u4e00\u4e2a2&#215;3\u7684\u68cb\u76d8\uff0c\u653e\u77400-5\u3002\u6bcf\u4e00\u6b650\u53ef\u4ee5\u548c\u4e0a\u4e0b\u5de6\u53f3\u7684\u4e00\u4e2a\u6570\u4ea4\u6362\u3002\u95ee\u9700\u8981\u591a\u5c11\u6b65\u53ef\u4ee5\u6784\u6210123450\u7684\u68cb\u76d8\u72b6\u6001\u3002<\/p>\n<p><strong>Problem:<\/strong><\/p>\n<p>On a 2&#215;3\u00a0<code>board<\/code>, there are 5 tiles represented by the integers 1 through 5, and an empty square represented by 0.<\/p>\n<p>A move consists of choosing\u00a0<code>0<\/code>\u00a0and a 4-directionally adjacent number and swapping it.<\/p>\n<p>The state of the board is\u00a0<em>solved<\/em>\u00a0if and only if the\u00a0<code>board<\/code>\u00a0is\u00a0<code>[[1,2,3],[4,5,0]].<\/code><\/p>\n<p>Given a puzzle board, return the least number of moves required so that the state of the board is solved. If it is impossible for the state of the board to be solved, return -1.<\/p>\n<p><strong>Examples:<\/strong><\/p>\n<pre class=\"\">Input: board = [[1,2,3],[4,0,5]]\r\nOutput: 1\r\nExplanation: Swap the 0 and the 5 in one move.\r\n<\/pre>\n<pre class=\"\">Input: board = [[1,2,3],[5,4,0]]\r\nOutput: -1\r\nExplanation: No number of moves will make the board solved.\r\n<\/pre>\n<pre class=\"\">Input: board = [[4,1,2],[5,0,3]]\r\nOutput: 5\r\nExplanation: 5 is the smallest number of moves that solves the board.\r\nAn example path:\r\nAfter move 0: [[4,1,2],[5,0,3]]\r\nAfter move 1: [[4,1,2],[0,5,3]]\r\nAfter move 2: [[0,1,2],[4,5,3]]\r\nAfter move 3: [[1,0,2],[4,5,3]]\r\nAfter move 4: [[1,2,0],[4,5,3]]\r\nAfter move 5: [[1,2,3],[4,5,0]]\r\n<\/pre>\n<pre class=\"\">Input: board = [[3,2,4],[1,5,0]]\r\nOutput: 14<\/pre>\n<p><strong>Solution: BFS<\/strong><\/p>\n<p>Time complexity: O(6!)<\/p>\n<p>Space complexity: O(6!)<\/p>\n<p>C++<\/p>\n<pre class=\"lang:c++ decode:true \">\/\/ Author: Huahua\r\n\/\/ Running time: 9 ms\r\nclass Solution {\r\npublic:\r\n  int slidingPuzzle(vector&lt;vector&lt;int&gt;&gt;&amp; board) {\r\n    constexpr int kRows = 2;\r\n    constexpr int kCols = 3; \r\n    string goal;\r\n    string start;\r\n    for (int i = 0; i &lt; board.size(); ++i)\r\n      for (int j = 0; j &lt; board[0].size(); ++j) {\r\n        start += (board[i][j] + '0');\r\n        goal += (i * kCols + j + 1) % (kRows * kCols) + '0'; \/\/ 12345...0\r\n    }\r\n    \r\n    if (start == goal) return 0;\r\n    \r\n    constexpr int dirs[4][2] = {{-1, 0}, {1, 0}, {0, 1}, {0, -1}};\r\n    \r\n    set&lt;string&gt; visited{start};\r\n    int steps = 0;\r\n    queue&lt;string&gt; q;\r\n    q.push(start);\r\n    while (!q.empty()) {\r\n      ++steps;\r\n      int size = q.size();\r\n      while (size-- &gt; 0) {\r\n        string s = q.front();\r\n        q.pop();\r\n        int p = s.find('0');\r\n        int y = p \/ kCols;\r\n        int x = p % kCols;        \r\n        for (int i = 0; i &lt; 4; ++i) {\r\n          int tx = x + dirs[i][0];\r\n          int ty = y + dirs[i][1];\r\n          if (tx &lt; 0 || ty &lt; 0 || tx &gt;= kCols || ty &gt;= kRows) continue;\r\n          int pp = ty * kCols + tx;\r\n          string t(s);\r\n          swap(t[p], t[pp]);          \r\n          if (visited.count(t)) continue;            \r\n          if (t == goal) return steps;\r\n          visited.insert(t);\r\n          q.push(t);\r\n        }\r\n      }      \r\n    }\r\n    return -1;\r\n  }\r\n};<\/pre>\n<p><strong>Simplified, only works on 3&#215;2 board<\/strong><\/p>\n<pre class=\"lang:c++ decode:true \">\/\/ Author: Huahua\r\n\/\/ Running time: 9 ms\r\nclass Solution {\r\npublic:\r\n  int slidingPuzzle(vector&lt;vector&lt;int&gt;&gt;&amp; board) {    \r\n    const string goal = \"123450\";\r\n    string start;\r\n    for (int i = 0; i &lt; board.size(); ++i)\r\n      for (int j = 0; j &lt; board[0].size(); ++j)\r\n        start += (board[i][j] + '0');\r\n    \r\n    if (start == goal) return 0;\r\n    \r\n    const vector&lt;vector&lt;int&gt;&gt; idx{{1, 3}, {0, 2, 4}, {1, 5}, {0, 4}, {1, 3, 5}, {2, 4}};\r\n    \r\n    set&lt;string&gt; visited{start};\r\n    int steps = 0;\r\n    queue&lt;pair&lt;string, int&gt;&gt; q;\r\n    q.emplace(start, start.find('0'));\r\n    while (!q.empty()) {\r\n      ++steps;\r\n      int size = q.size();\r\n      while (size-- &gt; 0) {\r\n        const auto&amp; p = q.front();\r\n        q.pop();\r\n        for (int index : idx[p.second]) { \r\n          string t(p.first);\r\n          swap(t[p.second], t[index]);\r\n          if (visited.count(t)) continue;            \r\n          if (t == goal) return steps;\r\n          visited.insert(t);\r\n          q.emplace(t, index);\r\n        }\r\n      }      \r\n    }\r\n    return -1;\r\n  }\r\n};<\/pre>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>\u9898\u76ee\u5927\u610f\uff1a\u7ed9\u4f60\u4e00\u4e2a2&#215;3\u7684\u68cb\u76d8\uff0c\u653e\u77400-5\u3002\u6bcf\u4e00\u6b650\u53ef\u4ee5\u548c\u4e0a\u4e0b\u5de6\u53f3\u7684\u4e00\u4e2a\u6570\u4ea4\u6362\u3002\u95ee\u9700\u8981\u591a\u5c11\u6b65\u53ef\u4ee5\u6784\u6210123450\u7684\u68cb\u76d8\u72b6\u6001\u3002 Problem: On a 2&#215;3\u00a0board, there are 5 tiles represented by the integers 1 through 5, and an empty square represented by 0. A move&#8230;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[44],"tags":[34],"class_list":["post-1768","post","type-post","status-publish","format-standard","hentry","category-searching","tag-bfs","entry","simple"],"_links":{"self":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/1768","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/comments?post=1768"}],"version-history":[{"count":8,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/1768\/revisions"}],"predecessor-version":[{"id":1776,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/1768\/revisions\/1776"}],"wp:attachment":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/media?parent=1768"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/categories?post=1768"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/tags?post=1768"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}