knbhd 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /* knbhd - Return the k-neighborhood of a node, i.e., allnodes
  2. * whose path length from the given node is <= k.
  3. * ARGV[] = k node_name
  4. */
  5. BEG_G {
  6. node_t ctr;
  7. int maxlen;
  8. graph_t comp = subg($, "kcomp");
  9. int sid = 0, eid = 0;
  10. int curlen;
  11. node_t curnode;
  12. int nlen[node_t];
  13. node_t stk[int];
  14. node_t other;
  15. edge_t e;
  16. if (ARGC != 2) {
  17. printf (2, "Two arguments required\n");
  18. exit(1);
  19. }
  20. if (!sscanf(ARGV[0],"%d",&maxlen)) {
  21. printf (2, "Improper length parameter \"%s\"\n", ARGV[0]);
  22. exit(1);
  23. }
  24. maxlen++; /* length of 0 means unset */
  25. ctr = isNode ($, ARGV[1]);
  26. if (!ctr) {
  27. printf (2, "node %s not found\n", ARGV[1]);
  28. exit(1);
  29. }
  30. subnode (comp,ctr);
  31. nlen[ctr] = 1;
  32. curnode = ctr;
  33. while (curnode) {
  34. curlen = nlen[curnode];
  35. if (curlen == maxlen) break;
  36. for (e = fstedge(curnode); e; e = nxtedge(e,curnode)) {
  37. other = e.head;
  38. if (other == curnode) other = e.tail;
  39. if (nlen[other]) continue; /* already seen */
  40. subnode(comp,other);
  41. nlen[other] = curlen+1;
  42. stk[eid++] = other;
  43. }
  44. if (sid < eid) curnode = stk[sid++];
  45. else curnode = NULL;
  46. }
  47. induce(comp);
  48. write(comp);
  49. }