Advertisement
Guest User

Untitled

a guest
Jun 17th, 2019
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.68 KB | None | 0 0
  1. // node defenition
  2. public class GraphNode
  3. {
  4. public GraphNode(int data, List<GraphNode> neighbours)
  5. {
  6. Data = data;
  7. Neighbours = neighbours;
  8. }
  9. }
  10.  
  11. // Loop on every Node, and find all k-distance neighbours
  12. public bool IfAllGraphNodesInKdistance1(List<GraphNode> nodes, int k)
  13. {
  14. for(int i=1; i< nodes.Count; i++)
  15. {
  16. if(FindKdistanceNeighboursInGraph(nodes[i], k).Count != nodes.Count)
  17. return false;
  18. }
  19. return true;
  20. }
  21. }
  22.  
  23.  
  24. // Find k-distance neighbours of a Node
  25. public HashSet<GraphNode> FindKdistanceNeighboursInGraph(GraphNode node, int distance )
  26. {
  27.  
  28. HashSet<GraphNode> resultHash = new HashSet<GraphNode>();
  29.  
  30. if (node != null && distance > 0)
  31. {
  32. HashSet<GraphNode> visited = new HashSet<GraphNode>();
  33. Queue<GraphNode> queue1 = new Queue<GraphNode>();
  34. Queue<GraphNode> queue2 = new Queue<GraphNode>();
  35. queue1.Enqueue(node);
  36. visited.Add(node);
  37. int currentDistance = 0;
  38. while (queue1.Count > 0 && currentDistance < distance)
  39. {
  40. GraphNode current = queue1.Dequeue();
  41. foreach (GraphNode graphNode in current.Neighbours)
  42. {
  43. if (!visited.Contains(graphNode))
  44. {
  45. queue2.Enqueue(graphNode);
  46. visited.Add(graphNode);
  47. resultHash.Add(graphNode);
  48. }
  49. }
  50. if (queue1.Count == 0)
  51. {
  52. queue1 = queue2;
  53. queue2 = new Queue<GraphNode>();
  54. currentDistance++;
  55. }
  56. }
  57. }
  58. resultHash.Add(node); // if it will include current
  59. return resultHash;
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement