- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我正在尝试解决 this显然是初学者级别的问题。但甚至无法想出蛮力方法。
这里是问题陈述:
Johnny has some difficulty memorizing the small prime numbers. So, his computer science teacher has asked him to play with the following puzzle game frequently.
The puzzle is a 3x3 board consisting of numbers from 1 to 9. The objective of the puzzle is to swap the tiles until the following final state is reached:
1 2 3
4 5 6
7 8 9At each step, Johnny may swap two adjacent tiles if their sum is a prime number. Two tiles are considered adjacent if they have a common edge.
Help Johnny to find the shortest number of steps needed to reach the goal state.
Input
The first line contains t, the number of test cases (about 50). Then t test cases follow. Each test case consists of a 3x3 table describing a puzzle which Johnny would like to solve.
The input data for successive test cases is separated by a blank line.
Output
For each test case print a single line containing the shortest number of steps needed to solve the corresponding puzzle. If there is no way to reach the final state, print the number -1.
Example
Input:
2
7 3 2
4 1 5
6 8 9
9 8 5
2 4 1
3 7 6Output:
6
-1
最佳答案
这是 Python 的开始,用于查找从一开始就可以到达的所有板的距离。
start = '123456789'
needed_moves = {start: 0}
work_queue = [start]
while (len(work_queue)):
board = work_queue.pop(0)
for next_board in next_move(board):
if next_board not in needed_moves:
needed_moves[next_board] = needed_moves[board] + 1
work_queue.append(next_board)
这是广度优先搜索的标准模式。只需为测试用例提供一个 next_move
函数和一些胶水就可以了。
对于深度优先搜索,只需将队列切换为堆栈。这实际上意味着 work_stack.pop()
弹出最后一个元素而不是 work_queue.pop(0)
获取第一个元素。
关于algorithm - 无法解决代码厨师难题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51894511/
我很困惑,我已经在互联网上阅读了很多,但我还是想不通。在这个设计中,可扩展性对我来说是一项重要的任务。 我正在制作一个门户网站,人们可以在这里出售他们的食物,或者可以去这个门户网站购买食物。 我正在考
我是一名优秀的程序员,十分优秀!