python 九宫重排_[蓝桥杯][历届试题]九宫重排 (Python代码)(bfs+集合)
ac代碼..可是官網還有兩組沒過..
```python
from collections import deque
class Node():
def __init__(self, arr, step, point):
self.arr = arr
self.step = step
self.point = point
def up(moveNode):
new_arr = Node(moveNode.arr, moveNode.step, moveNode.point)
new_arr.arr = list(new_arr.arr)
new_arr.arr[new_arr.point], new_arr.arr[new_arr.point - 3] = new_arr.arr[new_arr.point - 3], new_arr.arr[
new_arr.point]
new_arr.arr = ''.join(new_arr.arr)
new_arr.point -= 3
new_arr.step += 1
return new_arr
def down(moveNode):
new_arr = Node(moveNode.arr, moveNode.step, moveNode.point)
new_arr.arr = list(new_arr.arr)
new_arr.arr[new_arr.point], new_arr.arr[new_arr.point + 3] = new_arr.arr[new_arr.point + 3], new_arr.arr[
new_arr.point]
new_arr.arr = ''.join(new_arr.arr)
new_arr.point += 3
new_arr.step += 1
return new_arr
def left(moveNode):
new_arr = Node(moveNode.arr, moveNode.step, moveNode.point)
new_arr.arr = list(new_arr.arr)
new_arr.arr[new_arr.point], new_arr.arr[new_arr.point - 1] = new_arr.arr[new_arr.point - 1], new_arr.arr[
new_arr.point]
new_arr.arr = ''.join(new_arr.arr)
new_arr.point -= 1
new_arr.step += 1
return new_arr
def right(moveNode):
new_arr = Node(moveNode.arr, moveNode.step, moveNode.point)
new_arr.arr = list(new_arr.arr)
new_arr.arr[new_arr.point], new_arr.arr[new_arr.point + 1] = new_arr.arr[new_arr.point + 1], new_arr.arr[
new_arr.point]
new_arr.arr = ''.join(new_arr.arr)
new_arr.point += 1
new_arr.step += 1
return new_arr
def check(node):
if node == end:
return True
else:
return False
start = input()
end = input()
for i in range(9):
if start[i] == ".":
point = i
break
node = Node(start, 0, point)
visited = set()
queue = deque()
queue.append(node)
while queue:
moveNode = queue.popleft()
moveStr = moveNode.arr
if moveStr not in visited:
visited.add(moveStr)
point = moveNode.point
if check(moveNode.arr):
print(moveNode.step)
break
if moveNode.point > 2:
queue.append(up(moveNode))
if moveNode.point < 6:
queue.append(down(moveNode))
if moveNode.point != 0 and moveNode.point != 3 and moveNode.point != 6:
queue.append(left(moveNode))
if moveNode.point != 2 and moveNode.point != 5 and moveNode.point != 8:
queue.append(right(moveNode))
```
0.0分
1 人評分
總結
以上是生活随笔為你收集整理的python 九宫重排_[蓝桥杯][历届试题]九宫重排 (Python代码)(bfs+集合)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: wince手机投屏代码_除了 iOS,这
- 下一篇: java 主题爬虫_主题爬虫 - 长颈鹿