Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- static class Test
- {
- private static void Main()
- {
- var root = new QuadNode();
- root.Split(10); // 1398074 nodes
- root.LinkNodes();
- var stopwatch = new Stopwatch();
- const int iterations = 100;
- stopwatch.Restart();
- for (int i = 0; i < iterations; i++)
- {
- root.TraverseRecursivly(a => { });
- }
- stopwatch.Stop();
- Console.WriteLine("TraverseRecursivly elapsed time: {0}ms", stopwatch.ElapsedMilliseconds);
- stopwatch.Restart();
- for (int i = 0; i < iterations; i++)
- {
- root.TraverseIteratively(a => { });
- }
- stopwatch.Stop();
- Console.WriteLine("TraverseIteratively elapsed time: {0}ms", stopwatch.ElapsedMilliseconds);
- Console.ReadKey();
- }
- }
- class QuadNode
- {
- private QuadNode topLeft;
- private QuadNode topRight;
- private QuadNode bottomRight;
- private QuadNode bottomLeft;
- private QuadNode next;
- public void LinkNodes()
- {
- var queue = new Queue<QuadNode>();
- queue.Enqueue(this);
- QuadNode last = null;
- while (queue.Count > 0)
- {
- var node = queue.Dequeue();
- if (last != null)
- last.next = node;
- if (node.topLeft != null)
- queue.Enqueue(node.topLeft);
- if (node.topRight != null)
- queue.Enqueue(node.topRight);
- if (node.bottomRight != null)
- queue.Enqueue(node.bottomRight);
- if (node.bottomLeft != null)
- queue.Enqueue(node.bottomLeft);
- last = node;
- }
- }
- public void Split(int depth)
- {
- if (depth <= 0)
- return;
- topLeft = new QuadNode();
- topRight = new QuadNode();
- bottomRight = new QuadNode();
- bottomLeft = new QuadNode();
- depth--;
- topLeft.Split(depth);
- topRight.Split(depth);
- bottomRight.Split(depth);
- bottomLeft.Split(depth);
- }
- public void TraverseRecursivly(Action<QuadNode> action)
- {
- action(this);
- if (topLeft != null)
- topLeft.TraverseRecursivly(action);
- if (topRight != null)
- topRight.TraverseRecursivly(action);
- if (bottomRight != null)
- bottomRight.TraverseRecursivly(action);
- if (bottomLeft != null)
- bottomLeft.TraverseRecursivly(action);
- }
- public void TraverseIteratively(Action<QuadNode> action)
- {
- QuadNode node = this;
- while (node != null)
- {
- action(node);
- node = node.next;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement