在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ On a 2x3 A move consists of choosing The state of the board is solved if and only if the 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. Examples: Input: board = [[1,2,3],[4,0,5]] Output: 1 Explanation: Swap the 0 and the 5 in one move. Input: board = [[1,2,3],[5,4,0]] Output: -1 Explanation: No number of moves will make the board solved. Input: board = [[4,1,2],[5,0,3]] Output: 5 Explanation: 5 is the smallest number of moves that solves the board. An example path: After move 0: [[4,1,2],[5,0,3]] After move 1: [[4,1,2],[0,5,3]] After move 2: [[0,1,2],[4,5,3]] After move 3: [[1,0,2],[4,5,3]] After move 4: [[1,2,0],[4,5,3]] After move 5: [[1,2,3],[4,5,0]] Input: board = [[3,2,4],[1,5,0]] Output: 14 Note:
在一个 2 x 3 的板上( 一次移动定义为选择 最终当板 给出一个谜板的初始状态,返回最少可以通过多少次移动解开谜板,如果不能解开谜板,则返回 -1 。 示例: 输入:board = [[1,2,3],[4,0,5]] 输出:1 解释:交换 0 和 5 ,1 步完成 输入:board = [[1,2,3],[5,4,0]] 输出:-1 解释:没有办法完成谜板 输入:board = [[4,1,2],[5,0,3]] 输出:5 解释: 最少完成谜板的最少移动次数是 5 , 一种移动路径: 尚未移动: [[4,1,2],[5,0,3]] 移动 1 次: [[4,1,2],[0,5,3]] 移动 2 次: [[0,1,2],[4,5,3]] 移动 3 次: [[1,0,2],[4,5,3]] 移动 4 次: [[1,2,0],[4,5,3]] 移动 5 次: [[1,2,3],[4,5,0]] 输入:board = [[3,2,4],[1,5,0]] 输出:14 提示:
Runtime: 56 ms
Memory Usage: 19.2 MB
1 class Solution { 2 func slidingPuzzle(_ board: [[Int]]) -> Int { 3 var res:Int = 0 4 var visited:Set<[[Int]]> = Set<[[Int]]>() 5 var q:[([[Int]],[Int])] = [([[Int]],[Int])]() 6 var correct:[[Int]] = [[1, 2, 3],[4, 5, 0]] 7 var dirs:[[Int]] = [[0, -1],[-1, 0],[0, 1],[1, 0]] 8 for i in 0..<2 9 { 10 for j in 0..<3 11 { 12 if board[i][j] == 0 13 { 14 q.append((board, [i, j])) 15 } 16 } 17 } 18 while(!q.isEmpty) 19 { 20 for i in stride(from:q.count - 1,through:0,by:-1) 21 { 22 var t:[[Int]] = q.first!.0 23 var zero:[Int] = q.first!.1 24 q.removeFirst() 25 if t == correct 26 { 27 return res 28 } 29 visited.insert(t) 30 for dir in dirs 31 { 32 var x:Int = zero[0] + dir[0] 33 var y:Int = zero[1] + dir[1] 34 if x < 0 || x >= 2 || y < 0 || y >= 3 35 { 36 continue 37 } 38 var cand:[[Int]] = t 39 var temp:Int = cand[zero[0]][zero[1]] 40 cand[zero[0]][zero[1]] = cand[x][y] 41 cand[x][y] = temp 42 if visited.contains(cand) {continue} 43 q.append((cand,[x,y])) 44 } 45 } 46 res += 1 47 } 48 return -1 49 } 50 }
|
请发表评论