Created
March 29, 2017 20:54
-
-
Save hermesespinola/15cf66af8edf059df9f38c6c879db0cb to your computer and use it in GitHub Desktop.
Unity Breath and Depth first search
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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