protected override void SolveThread(CancellationToken token) { //start Breadth-First Search HashSet <ulong> visitedStates = new HashSet <ulong>(); Queue <HanoiNode> queue = new Queue <HanoiNode>(); queue.Enqueue(new HanoiNode(startState)); while (queue.Count > 0) { if (token.IsCancellationRequested) { token.ThrowIfCancellationRequested(); } HanoiNode node = queue.Dequeue(); if (visitedStates.Contains(node.state)) { continue; } visitedStates.Add(node.state); for (byte i = 0; i < pegCount; ++i) { for (byte j = 0; j < pegCount; ++j) { if (i == j) { continue; } ulong possibleState = HanoiOperations.Move(node.state, diskCount, i, j); if (node.state != possibleState) { if (!visitedStates.Contains(possibleState)) { HanoiNode possibleNode = new HanoiNode(possibleState, ref node); if (endState == possibleState) { endNode = possibleNode; VisitedStates = visitedStates.Count; visitedStates.GetEnumerator().Dispose(); return; } queue.Enqueue(possibleNode); } } } } } VisitedStates = visitedStates.Count; visitedStates.GetEnumerator().Dispose(); }
private void ReconstructPath(PuzzleSolver puzzleSolver) { HanoiNode currentNode = puzzleSolver.endNode; while (currentNode.parent != null) { ulong tempState1 = currentNode.state; ulong tempState2 = currentNode.parent != null ? currentNode.parent.state : 0; for (int i = 0; i < diskCount; ++i) { if (tempState1 % 10 != tempState2 % 10) { solution.Add(new Move((byte)(tempState2 % 10), (byte)(tempState1 % 10))); } tempState1 /= 10; tempState2 /= 10; } currentNode = currentNode.parent; } solution.Reverse(); }