public static int CalcCostGBFS(node aNode) { // Calculate cost from node to end return(Math.Abs(endX - aNode.X) + Math.Abs(endY - aNode.Y)); }
// Greedy Best-First search public static List <node> GBFS(string[,] aMap) { // initalising node startNode = new node(startX, startY); node endNode = new node(endX, endY); node currentNode = startNode; Dictionary <node, node> Parents = new Dictionary <node, node>(); List <node> exploredNodes = new List <node>(); Stack <node> s = new Stack <node>(); // push startnode to stack startNode.totalCost = CalcCostGBFS(startNode); s.Push(startNode); while (s.Any()) { // get current node by popping currentNode = s.Pop(); // finished if found goal node if (aMap[currentNode.X, currentNode.Y] == aMap[endX, endY]) { return(tracePath(currentNode, Parents)); } exploredNodes.Add(currentNode); List <node> neighbours = getNeighbours(currentNode, aMap); neighbours.Reverse(); // reversing order so neighbours are in correct order for GBFS logic foreach (node n in neighbours) { node newNode = n; newNode.totalCost = CalcCostGBFS(newNode); if (!(exploredNodes.Contains(newNode))) { // put the neighour in at the top of the stack with the parent behind it // when it found a cheaper cost if (newNode.totalCost <= currentNode.totalCost) { s.Push(currentNode); s.Push(newNode); Parents[newNode] = currentNode; break; // found better cost so we break here } // otherwise, keep looking else { s.Push(newNode); Parents[newNode] = currentNode; } } } } return(tracePath(currentNode, Parents)); }