-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolver.cs
64 lines (50 loc) · 1.58 KB
/
Solver.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
using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Puzzle15
{
public abstract class Solver : ISolver
{
private List<State> closed = null;
public LinkedList<State> Solve(State initial, BackgroundWorker worker)
{
closed = new List<State>();
ClearOpen();
AddState(initial);
while (HasElements())
{
State s = NextState();
if (worker.CancellationPending)
break;
if (s.IsSolution())
return FindPath(s);
closed.Add(s);
LinkedList<State> moves = s.GetPossibleMoves();
foreach (State move in moves)
if (!closed.Contains(move))
AddState(move);
}
return null;
}
public int GetVistedStateCount()
{
return closed.Count;
}
private LinkedList<State> FindPath(State solution)
{
LinkedList<State> path = new LinkedList<State>();
while (solution != null)
{
path.AddFirst(solution);
solution = solution.Parent;
}
return path;
}
protected abstract bool HasElements();
protected abstract State NextState();
protected abstract void AddState(State state);
protected abstract void ClearOpen();
}
}