-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution773.cs
79 lines (66 loc) · 1.98 KB
/
Solution773.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
using System.Text;
using LeetCode.DataStructures;
namespace LeetCode.Solutions;
public class Solution773
{
/// <summary>
/// 773. Sliding Puzzle - Hard
/// <a href="https://leetcode.com/problems/sliding-puzzle">See the problem</a>
/// </summary>
public int SlidingPuzzle(int[][] board)
{
var target = "123450";
var start = "";
// Flatten the board to a string
for (var i = 0; i < 2; i++)
{
for (var j = 0; j < 3; j++)
{
start += board[i][j].ToString();
}
}
// If the starting state is already the target
if (start == target) return 0;
// Map of possible moves for each position in the 2x3 board
int[][] moves = [
[1, 3],
[0, 2, 4],
[1, 5],
[0, 4],
[1, 3, 5],
[2, 4]
];
var queue = new Queue<(string, int)>(); // (board configuration, move count)
var visited = new HashSet<string>();
queue.Enqueue((start, 0));
visited.Add(start);
while (queue.Count > 0)
{
var (current, steps) = queue.Dequeue();
var zeroIndex = current.IndexOf('0');
// Generate all possible moves
foreach (var move in moves[zeroIndex])
{
var newConfig = Swap(current, zeroIndex, move);
if (newConfig == target)
{
return steps + 1; // Found solution
}
if (!visited.Contains(newConfig))
{
visited.Add(newConfig);
queue.Enqueue((newConfig, steps + 1));
}
}
}
return -1; // Unsolvable case
}
private string Swap(string s, int i, int j)
{
var arr = s.ToCharArray();
var temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
return new string(arr);
}
}