小黑代码
class Solution:
def slidingPuzzle(self, board: List[List[int]]) -> int:
boards = [board]
target = [[1, 2, 3], [4, 5, 0]]
if board == target:
return 0
m = len(board)
n = len(board[0])
x = y = -1
for i in range(m):
for j in range(n):
if not board[i][j]:
x = i
y = j
break
q = collections.deque([[(x, y) ,copy.deepcopy(board), 0]])
while q:
(x, y), board, num = q.popleft()
for di in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
new_x = x + di[0]
new_y = y + di[1]
if 0 <= new_x < m and 0 <= new_y < n:
new_board = copy.deepcopy(board)
new_board[x][y], new_board[new_x][new_y] = new_board[new_x][new_y], new_board[x][y]
if new_board == target:
return num + 1
if new_board not in boards:
boards.append(new_board)
q.append([(new_x, new_y), new_board, num+1])
return -1
宽度优先搜索
class Solution:
NEIGHBOURS = [[1, 3], [0, 2, 4], [1, 5], [0, 4], [1, 3, 5], [2, 4]]
def slidingPuzzle(self, board: List[List[int]]) -> int:
def get(status):
arr = list(status)
i = arr.index('0')
for t in self.NEIGHBOURS[i]:
arr[i], arr[t] = arr[t], arr[i]
yield ''.join(arr)
arr[i], arr[t] = arr[t], arr[i]
status = ''.join([''.join([str(i) for i in line]) for line in board])
target = '123450'
if status == target:
return 0
q = collections.deque([(status, 0)])
seen = set()
while q:
status, count = q.popleft()
for str_ in get(status):
if str_ == target:
return count + 1
if str_ not in seen:
q.append((str_, count+1))
seen.add(str_)
return -1
A*算法
class Astar(object):
def __init__(self, status, g):
self.status = status
self.g = g
self.h = Astar.getH(status)
self.f = self.g + self.h
@staticmethod
def getH(status):
dist = [
[0,1,2,1,2,3],
[1,0,1,2,1,2],
[2,1,0,3,2,1],
[1,2,3,0,1,2],
[2,1,2,1,0,1],
[3,2,1,2,1,0]
]
ret = 0
for i in range(len(status)):
if status[i] != '0':
ret += dist[i][int(status[i])-1]
return ret
def __lt__(self, other):
return self.f < other.f
class Solution:
def slidingPuzzle(self, board: List[List[int]]) -> int:
neighbors = [(1, 3), (0, 2, 4), (1, 5), (0, 4), (1, 3, 5), (2, 4)]
def get(status):
arr = list(status)
i = arr.index('0')
for t in neighbors[i]:
arr[t], arr[i] = arr[i], arr[t]
yield ''.join(arr)
arr[t], arr[i] = arr[i], arr[t]
str_ = ''.join([''.join([str(c) for c in line]) for line in board])
if str_ == '123450':
return 0
seen = set([str_])
q = [Astar(str_, 0)]
while q:
top = heapq.heappop(q)
status = top.status
g = top.g
for str_ in get(status):
if str_ == '123450':
return g+1
if str_ not in seen:
seen.add(str_)
heapq.heappush(q, Astar(str_, g+1))
return -1
小黑生活
半马成绩出来啦
早餐宇飞牛肉面
到公司来个太平洋桃花咖啡
肚子火气大,午饭就俩水果
晚饭吉野家鸡肉饭
晚上从朱辛庄绕远回家
走个罐排排火
回家喝个小酒
午餐宫保鸡丁饭
午后咖啡
晚饭牛杂面套餐
晚上坐5号线回家
给中老黑做个表情包啦
回去烫个头,这段时间折磨的我,理发师说我状态不如两个月前好了hhhh
回去把上次马拉松发的面给吃了
早上来杯奶油咖啡+曲奇
午饭一块儿披萨+饮料
盲审通过了,成绩还不错,继续加油