diff --git a/LeetCode/Sliding Puzzle.java b/LeetCode/Sliding Puzzle.java new file mode 100644 index 00000000..822eb563 --- /dev/null +++ b/LeetCode/Sliding Puzzle.java @@ -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 vis = new HashSet<>(); // Track visited configurations + Queue 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 + } +} \ No newline at end of file