Skip to content

Instantly share code, notes, and snippets.

@hermesespinola
Created March 29, 2017 20:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hermesespinola/15cf66af8edf059df9f38c6c879db0cb to your computer and use it in GitHub Desktop.
Save hermesespinola/15cf66af8edf059df9f38c6c879db0cb to your computer and use it in GitHub Desktop.
Unity Breath and Depth first search
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Pathfinding {
public static List<Node> Depthwise(Node start, Node end) {
Stack<Node> work = new Stack<Node> ();
List<Node> visited = new List<Node> ();
work.Push (start);
visited.Add (start);
start.history = new List<Node> ();
while(work.Count > 0){
Node current = work.Pop ();
if (current == end) {
List<Node> result = current.history;
result.Add (current);
return result;
} else {
for(int i = 0; i < current.neighbors.Length; i++){
Node currentChild = current.neighbors [i];
if(!visited.Contains(currentChild)){
work.Push (currentChild);
visited.Add (currentChild);
currentChild.history = new List<Node> (current.history);
currentChild.history.Add (current);
}
}
}
}
return null;
}
public static List<Node> Breadthwise(Node start, Node end) {
Queue<Node> work = new Queue<Node>();
List<Node> visited = new List<Node>();
work.Enqueue (start);
visited.Add (start);
start.history = new List<Node>();
while(work.Count > 0){
Node current = work.Dequeue ();
if(current == end){
// we found a solution!!
List<Node> result = current.history;
result.Add (current);
return result;
} else {
for(int i = 0; i < current.neighbors.Length; i++){
Node currentChild = current.neighbors[i];
if(!visited.Contains(currentChild)){
work.Enqueue (currentChild);
visited.Add (currentChild);
currentChild.history = new List<Node> (current.history);
currentChild.history.Add (current);
}
}
}
}
// No availabe path
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment