




Sponsored
Sponsored
Time Complexity: O(1) - There are a constant number of states (720) due to permutation limits.
Space Complexity: O(1) - As with time, space usage peaks at 720 given state permutations.
1using System;
2using System.Collections.Generic;
3
4public class Solution {
5    public int SlidingPuzzle(int[][] board) {
6        string start = string.Join("", board[0]) + string.Join("", board[1]);
7        string target = "123450";
8        int[][] neighbors = {
9            new int[] {1, 3},
10            new int[] {0, 2, 4},
11            new int[] {1, 5},
12            new int[] {0, 4},
13            new int[] {3, 1, 5},
14            new int[] {2, 4}
15        };
16        Queue<(string, int)> queue = new Queue<(string, int)>();
17        queue.Enqueue((start, 0));
18        HashSet<string> visited = new HashSet<string> { start };
19        while (queue.Count > 0) {
20            (string status, int steps) = queue.Dequeue();
21            if (status == target) return steps;
22            int zeroIndex = status.IndexOf('0');
23            foreach (int adj in neighbors[zeroIndex]) {
24                char[] newStatus = status.ToCharArray();
25                (newStatus[zeroIndex], newStatus[adj]) = (newStatus[adj], newStatus[zeroIndex]);
26                string newBoard = new string(newStatus);
27                if (!visited.Contains(newBoard)) {
28                    visited.Add(newBoard);
29                    queue.Enqueue((newBoard, steps + 1));
30                }
31            }
32        }
33        return -1;
34    }
35}In this C# solution, BFS is applied to find the minimum swaps to reach the solution. By treating tile positions as a linear string, we swap positions of '0', track visited states to avoid redundancy, and find optimized pathways quickly.
Time Complexity: O((6! = 720) log(720))
Space Complexity: O(720), based on the number of states handled.
1import java.util.*;
2
3
This Java code implements the A* search algorithm to tackle the sliding puzzle. Nodes are compared based on the cost estimation which combines depth and heuristic calculations. Using Manhattan distance as a heuristic ensures the solution is efficiently discovered through optimal path estimation.