Libraryless. Click here for Pure Java version (3388L/19K).
1 | // A is node type, B is link type |
2 | sclass BreadthFirstPathFinder_withLinkType<A, B> implements Steppable { |
3 | new LinkedList<A> queue; |
4 | new MultiMap<A, Pair<A, B>> links; // backwards (child -> parent) |
5 | IF1<A, Cl<Pair<A, B>>> getChildren; // must set |
6 | |
7 | *() {} |
8 | *(IF1<A, Cl<Pair<A, B>>> *getChildren) {} |
9 | *(IF1<A, Cl<Pair<A, B>>> *getChildren, A startNode) { add(startNode); } |
10 | |
11 | void add(A a) { |
12 | add(a, null, null); |
13 | } |
14 | |
15 | void add(A a, A prev, B linkType) { |
16 | if (!links.containsKey(a)) { |
17 | links.put(a, prev == null ?: pair(prev, linkType)); |
18 | queue.add(a); |
19 | } |
20 | } |
21 | |
22 | public bool step() { |
23 | ping(); |
24 | if (empty(queue)) false; |
25 | A a = popFirst(queue); |
26 | fOr (Pair<A, B> link : getChildren.get(a)) |
27 | add(link.a, a, link.b); |
28 | true; |
29 | } |
30 | |
31 | bool nodeReached(A a) { |
32 | ret links.containsKey(a); |
33 | } |
34 | |
35 | Cl<A> getBackLinks(A a) { |
36 | ret pairsA(links.get(a)); |
37 | } |
38 | |
39 | Cl<Pair<A, B>> getBackLinksWithTypes(A a) { |
40 | ret links.get(a); |
41 | } |
42 | |
43 | LPair<A, B> examplePathWithTypes(A start, A dest) { |
44 | new LPair<A, B> path; |
45 | A node = dest; |
46 | path.add(pair(node, null)); // dest node has no link type |
47 | while ping (node != start) { |
48 | Pair<A, B> link = first(getBackLinksWithTypes(node)); |
49 | ifdef BreadthFirstPathFinder_debug |
50 | printVars_str examplePathWithTypes(+node, +link); |
51 | endifdef |
52 | if (link == null) null; // no path found |
53 | path.add(link); |
54 | node = link.a; |
55 | } |
56 | ret reversed(path); |
57 | } |
58 | } |
Began life as a copy of #1030913
download show line numbers debug dex old transpilations
Travelled to 4 computer(s): bhatertpkbcr, mqqgnosmbjvj, pyentgdyhuwx, vouqrxazstgt
No comments. add comment
Snippet ID: | #1030919 |
Snippet name: | BreadthFirstPathFinder_withLinkType [OK] |
Eternal ID of this version: | #1030919/11 |
Text MD5: | dc284d7f93830e632d208dd9f6c71bda |
Transpilation MD5: | d348672b39afc4ebe3b0371594064aef |
Author: | stefan |
Category: | javax |
Type: | JavaX fragment (include) |
Public (visible to everyone): | Yes |
Archived (hidden from active list): | No |
Created/modified: | 2021-04-10 19:23:55 |
Source code size: | 1533 bytes / 58 lines |
Pitched / IR pitched: | No / No |
Views / Downloads: | 260 / 502 |
Version history: | 10 change(s) |
Referenced in: | [show references] |