Skip to content

Commit

Permalink
Create Sliding Puzzle.java (#589)
Browse files Browse the repository at this point in the history
  • Loading branch information
avnisinngh authored Jan 23, 2025
1 parent cc97ccd commit 6fc9883
Showing 1 changed file with 49 additions and 0 deletions.
49 changes: 49 additions & 0 deletions LeetCode/Sliding Puzzle.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
class Solution {
public int slidingPuzzle(int[][] board) {
// Directions for possible swaps based on '0' position
int[][] dir = {{1, 3}, {0, 2, 4}, {1, 5}, {0, 4}, {1, 3, 5}, {2, 4}};
String target = "123450";
Set<String> vis = new HashSet<>(); // Track visited configurations
Queue<String> q = new LinkedList<>();
String start = "";

// Convert 2D board to a single string
for (int[] row : board) {
for (int col : row) {
start += col;
}
}

q.offer(start);
vis.add(start);
int step = 0;

// Perform BFS
while (!q.isEmpty()) {
int size = q.size();
while (size-- > 0) {
String current = q.poll();

// Check if target is reached
if (current.equals(target)) return step;

int zero = current.indexOf('0'); // Find position of '0'

// Generate next moves
for (int move : dir[zero]) {
StringBuilder next = new StringBuilder(current);
char temp = next.charAt(zero);
next.setCharAt(zero, next.charAt(move));
next.setCharAt(move, temp);

if (!vis.contains(next.toString())) { // Add unvisited states to the queue
vis.add(next.toString());
q.offer(next.toString());
}
}
}
step++;
}
return -1; // Return -1 if target is unreachable
}
}

0 comments on commit 6fc9883

Please sign in to comment.