773. 滑动谜题
在一个 2 x 3 的板上(board)有 5 块砖瓦,用数字 1~5 来表示, 以及一块空缺用 0 来表示.
一次移动定义为选择 0 与一个相邻的数字(上下左右)进行交换.
最终当板 board 的结果是 [[1,2,3],[4,5,0]] 谜板被解开。
给出一个谜板的初始状态,返回最少可以通过多少次移动解开谜板,如果不能解开谜板,则返回 -1 。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sliding-puzzle
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Set;
class Solution {
// 0 1 2
// 3 4 5
private static int[][] operations = {{1, 3}, {0, 2, 4}, {1, 5}, {0, 4}, {1, 3, 5}, {2, 4}};
private void swap(char[] str, int a, int b) {
char t = str[a];
str[a] = str[b];
str[b] = t;
}
private String parseString(int[][] board) {
StringBuilder ans = new StringBuilder();
for (int i = 0; i < board.length; ++i) {
for (int j = 0; j < board[0].length; ++j) {
ans.append(board[i][j]);
}
}
return ans.toString();
}
private int getZeroIndex(int[][] board) {
int ans = 0;
for (int i = 0; i < board.length; ++i) {
for (int j = 0; j < board[0].length; ++j) {
if (board[i][j] == 0) {
return ans;
}
ans++;
}
}
return ans;
}
public int slidingPuzzle(int[][] board) {
if (board == null || board.length == 0 || board[0].length == 0) {
return -1;
}
String start = parseString(board);
String end = "123450";
Set<String> visited = new HashSet<>();
Queue<Info> queue = new LinkedList<>();
queue.offer(new Info(start, 0, getZeroIndex(board)));
visited.add(start);
while (!queue.isEmpty()) {
Info node = queue.poll();
if (node.value.equals(end)) {
return node.step;
}
String s = node.value;
for (int x : operations[node.zeroIndex]) {
char[] copy = s.toCharArray();
swap(copy, node.zeroIndex, x);
String num = new String(copy);
if (!visited.contains(num)) {
queue.offer(new Info(num, node.step + 1, x));
visited.add(num);
}
}
}
return -1;
}
}
class Info {
String value;
int step;
int zeroIndex;
public Info(String value, int step, int zeroIndex) {
this.value = value;
this.step = step;
this.zeroIndex = zeroIndex;
}
}
心之所向,素履以往 生如逆旅,一苇以航
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】