-
Notifications
You must be signed in to change notification settings - Fork 44
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
cc97ccd
commit 6fc9883
Showing
1 changed file
with
49 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} | ||
} |