So let's start!
You will need same functions mentioned at Breadth-First example; you have to change Frontier and it's functions for Stack, Node.cs will remain same, you can reach it with this address: Node.cs.
Your main will initialize DFS for this example;
static void Main(string[] args)
{
int[] ex = { 1, 2, 3, 0, 4, 5, 6, 7, 8 };
DFS_dfs = new DFS(ex);
_dfs.Solve();
}
DFS.cs file will have;
private Stack<Node> Frontier instead of private Queue<Node> Frontier.
It will contain;
class DFS
{
int[] GoalState = { 0, 1, 2, 3, 4, 5, 6, 7, 8 };
private Stack<Node> Frontier;
private HashSet<Node> Solution;
private Node RootNode;
public DFS(int[] StartState)
{}
public void Solve()
{}
public IEnumerable<Node> GenerateSuccessor(Node ParentNode)
{}
public bool IsGoalState(int[] State)
{}
public void WriteSolution()
{}
}
The only change is in Solve function; to add an item to a Stack you use Push command instead of Enqueue which used in Queues, just like Pop command for Dequeue.
Solve function will be;
- public void Solve()
- {
- Node ActiveNode = RootNode;
- bool IsSolved = false;
- while (!IsGoalState(ActiveNode.GetState()))
- {
- Solution.Add(ActiveNode);
- foreach(Node successor in GenerateSuccessor(ActiveNode))
- {
- Frontier.Push(successor);
- if (IsGoalState(successor.GetState()))
- {
- IsSolved = true;
- Solution.Add(successor);
- break;
- }
- }
- if (IsSolved)
- break;
- ActiveNode = Frontier.Pop();
- }
- WriteSolution();
- }
It is not fast as BFS, and generally you don't get much result in 8-Puzzle problems with Depth First Search, because it just create successors over a branch, if that branch doesn't bring us to the solution, we might never find it. So, DFS is not complete.
Source Files:
DFS.cs
Node.cs
Program.cs
Hiç yorum yok:
Yorum Gönder