Created
April 28, 2016 12:35
-
-
Save geoand/d70be5a7bb1ccae327942a8fc0360e36 to your computer and use it in GitHub Desktop.
Groovy implementation of a simplistic Iterative deepening 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
import groovy.transform.TailRecursive | |
import groovy.transform.ToString | |
@ToString(includePackage = false) | |
class Node<T> { | |
T data | |
List<Node<T>> nodes = [] | |
} | |
final builder = new ObjectGraphBuilder(classLoader: getClass().classLoader) | |
final Node<String> root = builder.node(data: '1') { | |
node(data: '2a') { | |
node(data: '3a1') | |
node(data: '3a2') | |
} | |
node(data: '2b') { | |
node(data: '3a') | |
node(data: '3b') | |
node(data: '3c') { | |
node(data: '4a') | |
} | |
} | |
} | |
def <T> boolean iddfs(Node<T> root, T item) { | |
if (!root) { | |
return true | |
} | |
final queue = new LinkedList<Node<T>>() | |
queue.add(root) | |
return iddfs_recursive(item, queue) | |
} | |
@TailRecursive | |
def static <T> boolean iddfs_recursive(T item, Queue<Node<T>> queue) { | |
if (queue.isEmpty()) { | |
return false | |
} | |
final first = queue.remove() | |
if (first.data == item) { | |
return true | |
} | |
queue.addAll(first.nodes) | |
return iddfs_recursive(item, queue) | |
} | |
assert iddfs(root, '1') | |
assert iddfs(root, '2a') | |
assert iddfs(root, '2b') | |
assert iddfs(root, '3a') | |
assert iddfs(root, '3b') | |
assert iddfs(root, '3c') | |
assert iddfs(root, '4a') | |
assert !iddfs(root, 'dummy') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment