Last active
March 3, 2022 17:28
-
-
Save iamSahdeep/39a62d6cdb0715d7e6fca87e7c1bf62c to your computer and use it in GitHub Desktop.
Breadth First Traversal + Depth First Traversal implemented in Dart (Recursive and Iterative both)
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
import 'dart:collection'; | |
const graph = { | |
"a": ["b", "c"], | |
"b": ["d"], | |
"c": ["e"], | |
"d": ["f"], | |
"e": [], | |
"f": [], | |
}; | |
List<String> stack = ["a"]; | |
Queue<String> queue = Queue(); | |
void main() { | |
queue.addFirst("a"); | |
print("Depth Iterative " + depthFirstSearchIterative().toString()); | |
print("Breadth Iterative " + breadthFirstSearchIterative().toString()); | |
print("Depth Recursive " + depthFirstSearchRecursive([], "a").toString()); | |
//have to use queue for recurive approach | |
queue.addFirst("a"); | |
//Don't worry if it doesn't match the iterative output, both are valid traversal | |
print("Breadth Recursive " + breadthFirstSearchRecursive([]).toString()); | |
} | |
/// Iterative Methods | |
List<String> depthFirstSearchIterative() { | |
List<String> output = []; | |
while (stack.isNotEmpty) { | |
List? branch = graph[stack.last]?.toList(); | |
output.add(stack.last); | |
stack.removeLast(); | |
while (branch!.isNotEmpty) { | |
stack.add(branch.last); | |
branch.removeLast(); | |
} | |
} | |
return output; | |
} | |
List<String> breadthFirstSearchIterative() { | |
List<String> output = []; | |
while (queue.isNotEmpty) { | |
List? branch = graph[queue.first]?.toList(); | |
output.add(queue.first); | |
queue.removeFirst(); | |
while (branch!.isNotEmpty) { | |
queue.add(branch.last); | |
branch.removeLast(); | |
} | |
} | |
return output; | |
} | |
///Recursive Methods | |
List<String> depthFirstSearchRecursive(List<String> output, String root) { | |
output.add(root); | |
List? branch = graph[root]?.toList(); | |
for (final item in branch!) { | |
depthFirstSearchRecursive(output, item); | |
} | |
return output; | |
} | |
List<String> breadthFirstSearchRecursive(List<String> output) { | |
if(queue.isEmpty){ | |
return output; | |
} | |
String item = queue.first; | |
queue.removeFirst(); | |
output.add(item); | |
for (final items in graph[item]!.toList()) { | |
queue.add(items); | |
} | |
breadthFirstSearchRecursive(output); | |
return output; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment