#
Junjie
9 天以前 dc3f9cc91759823ce59486f19b138be4b296a0f1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
package com.zy.common.utils;
 
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.core.common.SpringUtils;
import com.core.exception.CoolException;
import com.zy.asrs.entity.BasMap;
import com.zy.asrs.service.BasMapService;
import com.zy.common.model.NavigateNode;
import com.zy.core.enums.RedisKeyType;
import com.zy.core.enums.MapNodeType;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
 
/**
 * A*算法实现类
 */
public class NavigateSolution {
 
    private static final long REDIS_MAP_CACHE_TTL_SECONDS = 60 * 60 * 24L;
    private static final long MAP_CACHE_TTL_MS = 5000L;
    private static final Map<String, CachedNavigateMap> NAVIGATE_MAP_CACHE = new ConcurrentHashMap<>();
    private static final Map<String, CachedNavigateMapIndex> NAVIGATE_MAP_INDEX_CACHE = new ConcurrentHashMap<>();
 
    // Open表用优先队列
    public PriorityQueue<NavigateNode> Open = new PriorityQueue<NavigateNode>();
    //Close表用坐标key集合,O(1)查找
    public Set<String> Close = new HashSet<>();
    //用来存放已经出现过的结点。
    Map<String, Integer> bestGMap = new HashMap<>();
 
    public List<List<NavigateNode>> getStationMap(int lev) {
        return cloneNavigateMap(loadCachedNavigateMap("station", lev));
    }
 
    public NavigateMapIndex getStationMapIndex(int lev) {
        return loadCachedNavigateMapIndex("station", lev);
    }
 
    public List<List<NavigateNode>> getRgvTrackMap(int lev) {
        return cloneNavigateMap(loadCachedNavigateMap("rgv", lev));
    }
 
    private List<List<NavigateNode>> loadCachedNavigateMap(String mapType, int lev) {
        String cacheKey = mapType + ":" + lev;
        long now = System.currentTimeMillis();
        CachedNavigateMap cachedNavigateMap = NAVIGATE_MAP_CACHE.get(cacheKey);
        if (cachedNavigateMap != null && now - cachedNavigateMap.cacheAtMs <= MAP_CACHE_TTL_MS) {
            return cachedNavigateMap.navigateMap;
        }
 
        List<List<NavigateNode>> redisNavigateMap = loadNavigateMapFromRedis(mapType, lev);
        if (isValidNavigateMap(redisNavigateMap)) {
            enrichNavigateMapMetadata(redisNavigateMap);
            NAVIGATE_MAP_CACHE.put(cacheKey, new CachedNavigateMap(now, redisNavigateMap));
            return redisNavigateMap;
        }
        clearMapCache(lev);
 
        List<List<NavigateNode>> navigateNodeList = buildNavigateMap(mapType, lev);
        enrichNavigateMapMetadata(navigateNodeList);
        cacheNavigateMap(cacheKey, mapType, lev, navigateNodeList, now);
        return navigateNodeList;
    }
 
    private NavigateMapIndex loadCachedNavigateMapIndex(String mapType, int lev) {
        String cacheKey = mapType + ":" + lev;
        long now = System.currentTimeMillis();
        CachedNavigateMapIndex cachedNavigateMapIndex = NAVIGATE_MAP_INDEX_CACHE.get(cacheKey);
        if (cachedNavigateMapIndex != null && now - cachedNavigateMapIndex.cacheAtMs <= MAP_CACHE_TTL_MS) {
            return cachedNavigateMapIndex.navigateMapIndex;
        }
 
        List<List<NavigateNode>> navigateMap = loadCachedNavigateMap(mapType, lev);
        NavigateMapIndex navigateMapIndex = buildNavigateMapIndex(lev, navigateMap);
        NAVIGATE_MAP_INDEX_CACHE.put(cacheKey, new CachedNavigateMapIndex(now, navigateMapIndex));
        return navigateMapIndex;
    }
 
    public static void refreshAllMapCaches() {
        BasMapService basMapService = SpringUtils.getBean(BasMapService.class);
        List<Integer> levList = basMapService.getLevList();
        if (levList == null || levList.isEmpty()) {
            NAVIGATE_MAP_CACHE.clear();
            return;
        }
        LinkedHashSet<Integer> distinctLevSet = new LinkedHashSet<>(levList);
        for (Integer lev : distinctLevSet) {
            if (lev == null) {
                continue;
            }
            refreshMapCache(lev);
        }
    }
 
    public static void refreshMapCache(Integer lev) {
        if (lev == null) {
            return;
        }
        long now = System.currentTimeMillis();
        NavigateSolution navigateSolution = new NavigateSolution();
        List<List<NavigateNode>> stationMap = navigateSolution.buildNavigateMap("station", lev);
        navigateSolution.enrichNavigateMapMetadata(stationMap);
        navigateSolution.cacheNavigateMap("station:" + lev, "station", lev, stationMap, now);
        navigateSolution.cacheNavigateMapIndex("station:" + lev, lev, stationMap, now);
        List<List<NavigateNode>> rgvMap = navigateSolution.buildNavigateMap("rgv", lev);
        navigateSolution.enrichNavigateMapMetadata(rgvMap);
        navigateSolution.cacheNavigateMap("rgv:" + lev, "rgv", lev, rgvMap, now);
    }
 
    public static void clearMapCache(Integer lev) {
        if (lev == null) {
            return;
        }
        NAVIGATE_MAP_CACHE.remove("station:" + lev);
        NAVIGATE_MAP_CACHE.remove("rgv:" + lev);
        NAVIGATE_MAP_INDEX_CACHE.remove("station:" + lev);
        RedisUtil redisUtil = SpringUtils.getBean(RedisUtil.class);
        redisUtil.del(buildRedisCacheKey("station", lev), buildRedisCacheKey("rgv", lev));
    }
 
    private void cacheNavigateMap(String localCacheKey,
                                  String mapType,
                                  int lev,
                                  List<List<NavigateNode>> navigateNodeList,
                                  long cacheAtMs) {
        RedisUtil redisUtil = SpringUtils.getBean(RedisUtil.class);
        redisUtil.set(buildRedisCacheKey(mapType, lev),
                JSON.toJSONString(navigateNodeList),
                REDIS_MAP_CACHE_TTL_SECONDS);
        NAVIGATE_MAP_CACHE.put(localCacheKey, new CachedNavigateMap(cacheAtMs, navigateNodeList));
    }
 
    private void cacheNavigateMapIndex(String localCacheKey,
                                       int lev,
                                       List<List<NavigateNode>> navigateNodeList,
                                       long cacheAtMs) {
        NAVIGATE_MAP_INDEX_CACHE.put(localCacheKey, new CachedNavigateMapIndex(cacheAtMs, buildNavigateMapIndex(lev, navigateNodeList)));
    }
 
    private List<List<NavigateNode>> loadNavigateMapFromRedis(String mapType, int lev) {
        RedisUtil redisUtil = SpringUtils.getBean(RedisUtil.class);
        Object cachedValue = redisUtil.get(buildRedisCacheKey(mapType, lev));
        if (!(cachedValue instanceof String) || ((String) cachedValue).trim().isEmpty()) {
            return null;
        }
        try {
            return JSON.parseObject((String) cachedValue, new TypeReference<List<List<NavigateNode>>>() {});
        } catch (Exception ignore) {
            return null;
        }
    }
 
    private static String buildRedisCacheKey(String mapType, int lev) {
        return RedisKeyType.NAVIGATE_MAP_TEMPLATE_.key + mapType + "_" + lev;
    }
 
    private List<List<NavigateNode>> buildNavigateMap(String mapType, int lev) {
        BasMapService basMapService = SpringUtils.getBean(BasMapService.class);
        BasMap basMap = basMapService.getOne(new QueryWrapper<BasMap>().eq("lev", lev));
        if (basMap == null) {
            throw new CoolException("地图不存在");
        }
 
        List<List<JSONObject>> dataList = JSON.parseObject(basMap.getData(), List.class);
        List<List<NavigateNode>> navigateNodeList = new ArrayList<>();
        for (int i = 0; i < dataList.size(); i++) {
            List<JSONObject> row = dataList.get(i);
            List<NavigateNode> navigateNodeRow = new ArrayList<>();
            for (int j = 0; j < row.size(); j++) {
                JSONObject map = row.get(j);
                NavigateNode navigateNode = new NavigateNode(i, j);
 
                String nodeType = map.getString("type");
                String mergeType = map.getString("mergeType");
                String nodeValue = map.getString("value");
                if(nodeType == null) {
                    navigateNode.setValue(MapNodeType.DISABLE.id);
                } else if ("station".equals(mapType)
                        && (nodeType.equals("devp") || (nodeType.equals("merge") && "devp".equals(mergeType)))) {
                    navigateNode.setValue(MapNodeType.NORMAL_PATH.id);
                    JSONObject valueObj = JSON.parseObject(nodeValue);
                    List<String> directionList = valueObj == null || valueObj.getJSONArray("direction") == null
                            ? new ArrayList<>()
                            : valueObj.getJSONArray("direction").toJavaList(String.class);
                    navigateNode.setDirectionList(directionList);
                } else if ("station".equals(mapType) && nodeType.equals("rgv")) {
                    navigateNode.setValue(MapNodeType.NORMAL_PATH.id);
                    JSONObject newNodeValue = new JSONObject();
                    newNodeValue.put("rgvCalcFlag", 1);
                    nodeValue = JSON.toJSONString(newNodeValue);
 
                    List<String> directionList = new ArrayList<>();
                    directionList.add("top");
                    directionList.add("bottom");
                    directionList.add("left");
                    directionList.add("right");
                    navigateNode.setDirectionList(directionList);
                } else if ("rgv".equals(mapType) && nodeType.equals("rgv")) {
                    navigateNode.setValue(MapNodeType.NORMAL_PATH.id);
                    List<String> directionList = new ArrayList<>();
                    directionList.add("top");
                    directionList.add("bottom");
                    directionList.add("left");
                    directionList.add("right");
                    navigateNode.setDirectionList(directionList);
                } else {
                    navigateNode.setValue(MapNodeType.DISABLE.id);
                }
 
                navigateNode.setNodeType(nodeType);
                navigateNode.setNodeValue(nodeValue);
                applyNodeMetadata(navigateNode);
                navigateNodeRow.add(navigateNode);
            }
            navigateNodeList.add(navigateNodeRow);
        }
        return cropNavigateMap(navigateNodeList);
    }
 
    private List<List<NavigateNode>> cloneNavigateMap(List<List<NavigateNode>> sourceMap) {
        List<List<NavigateNode>> cloneMap = new ArrayList<>();
        for (List<NavigateNode> row : sourceMap) {
            List<NavigateNode> cloneRow = new ArrayList<>();
            for (NavigateNode node : row) {
                cloneRow.add(node == null ? null : node.clone());
            }
            cloneMap.add(cloneRow);
        }
        return cloneMap;
    }
 
    private void enrichNavigateMapMetadata(List<List<NavigateNode>> navigateMap) {
        if (navigateMap == null || navigateMap.isEmpty()) {
            return;
        }
        for (List<NavigateNode> row : navigateMap) {
            for (NavigateNode node : row) {
                applyNodeMetadata(node);
            }
        }
    }
 
    private void applyNodeMetadata(NavigateNode node) {
        if (node == null) {
            return;
        }
        if (node.getNodeValue() == null || node.getNodeValue().trim().isEmpty()) {
            if (node.getBridgeStationIds() == null) {
                node.setBridgeStationIds(Collections.emptyList());
            }
            if (node.getLiftTransfer() == null) {
                node.setLiftTransfer(Boolean.FALSE);
            }
            if (node.getRgvCalcFlag() == null) {
                node.setRgvCalcFlag(Boolean.FALSE);
            }
            return;
        }
        JSONObject valueObj = parseNodeValue(node.getNodeValue());
        if (valueObj == null) {
            if (node.getBridgeStationIds() == null) {
                node.setBridgeStationIds(Collections.emptyList());
            }
            if (node.getLiftTransfer() == null) {
                node.setLiftTransfer(Boolean.FALSE);
            }
            if (node.getRgvCalcFlag() == null) {
                node.setRgvCalcFlag(Boolean.FALSE);
            }
            return;
        }
        node.setStationId(valueObj.getInteger("stationId"));
        JSONArray bridgeStationArray = valueObj.getJSONArray("bridgeStationIds");
        if (bridgeStationArray == null || bridgeStationArray.isEmpty()) {
            node.setBridgeStationIds(Collections.emptyList());
        } else {
            node.setBridgeStationIds(Collections.unmodifiableList(new ArrayList<>(bridgeStationArray.toJavaList(Integer.class))));
        }
        Object isLiftTransfer = valueObj.get("isLiftTransfer");
        if (isLiftTransfer == null) {
            node.setLiftTransfer(Boolean.FALSE);
        } else {
            String isLiftTransferText = String.valueOf(isLiftTransfer);
            node.setLiftTransfer("1".equals(isLiftTransferText) || "true".equalsIgnoreCase(isLiftTransferText));
        }
        node.setRgvCalcFlag(valueObj.containsKey("rgvCalcFlag"));
    }
 
    private boolean isValidNavigateMap(List<List<NavigateNode>> navigateMap) {
        if (navigateMap == null || navigateMap.isEmpty() || navigateMap.get(0) == null || navigateMap.get(0).isEmpty()) {
            return false;
        }
 
        int activeNodeCount = 0;
        for (List<NavigateNode> row : navigateMap) {
            if (row == null || row.isEmpty()) {
                return false;
            }
            for (NavigateNode node : row) {
                if (node == null) {
                    return false;
                }
                if (node.getValue() == MapNodeType.DISABLE.id) {
                    continue;
                }
                activeNodeCount++;
                if (node.getNodeType() == null) {
                    return false;
                }
                if (node.getDirectionList() == null || node.getDirectionList().isEmpty()) {
                    return false;
                }
            }
        }
        return activeNodeCount > 0;
    }
 
    /**
     * 只保留参与路径计算的二维区域,去掉上下左右整片无效空白区。
     */
    private List<List<NavigateNode>> cropNavigateMap(List<List<NavigateNode>> navigateMap) {
        if (navigateMap == null || navigateMap.isEmpty() || navigateMap.get(0) == null || navigateMap.get(0).isEmpty()) {
            return navigateMap;
        }
 
        int minX = Integer.MAX_VALUE;
        int maxX = Integer.MIN_VALUE;
        int minY = Integer.MAX_VALUE;
        int maxY = Integer.MIN_VALUE;
        boolean hasActiveNode = false;
        for (int x = 0; x < navigateMap.size(); x++) {
            List<NavigateNode> row = navigateMap.get(x);
            if (row == null) {
                continue;
            }
            for (int y = 0; y < row.size(); y++) {
                NavigateNode node = row.get(y);
                if (node == null || node.getValue() == MapNodeType.DISABLE.id) {
                    continue;
                }
                hasActiveNode = true;
                minX = Math.min(minX, x);
                maxX = Math.max(maxX, x);
                minY = Math.min(minY, y);
                maxY = Math.max(maxY, y);
            }
        }
 
        if (!hasActiveNode) {
            return navigateMap;
        }
 
        List<List<NavigateNode>> croppedMap = new ArrayList<>();
        for (int x = minX; x <= maxX; x++) {
            List<NavigateNode> sourceRow = navigateMap.get(x);
            List<NavigateNode> croppedRow = new ArrayList<>();
            for (int y = minY; y <= maxY; y++) {
                NavigateNode sourceNode = sourceRow.get(y);
                NavigateNode targetNode = new NavigateNode(x - minX, y - minY);
                targetNode.setValue(sourceNode.getValue());
                targetNode.setNodeType(sourceNode.getNodeType());
                targetNode.setNodeValue(sourceNode.getNodeValue());
                targetNode.setDirectionList(sourceNode.getDirectionList() == null
                        ? null
                        : new ArrayList<>(sourceNode.getDirectionList()));
                croppedRow.add(targetNode);
            }
            croppedMap.add(croppedRow);
        }
        return croppedMap;
    }
 
    public NavigateNode astarSearchJava(List<List<NavigateNode>> map, NavigateNode start, NavigateNode end) {
        // 清理上次搜索的状态,防止复用实例导致记录残留
        this.Open.clear();
        this.Close.clear();
        this.bestGMap.clear();
        //把第一个开始的结点加入到Open表中
        this.Open.add(start);
        //主循环
        while (Open.size() > 0) {
            //取优先队列顶部元素并且把这个元素从Open表中删除
            NavigateNode current_node = Open.poll();
 
            if (current_node.getX() == end.getX() && current_node.getY() == end.getY()) {//找到目标结点就返回
                return current_node;
            }
 
            //将这个结点加入到Close表中
            Close.add(keyOf(current_node));
            //对当前结点进行扩展,得到一个四周结点的数组
            ArrayList<NavigateNode> neighbour_node = extend_current_node(map, current_node);
            //对这个结点遍历,看是否有目标结点出现
            for (NavigateNode node : neighbour_node) {
                // 已在关闭列表中的节点不再处理,避免父链反复改写形成环
                if (Close.contains(keyOf(node))) {
                    continue;
                }
                // G + H + E (对启发函数增加去拐点方案calcNodeExtraCost)
                int gCost = calcNodeExtraCost(current_node, node, end);
 
                //进行计算对G, F, H 等值
                node.setG(1 + gCost);
                node.init_node(current_node, end);
                node.setH(calcNodeCost(node, end));
                node.setF(node.getG() + node.getH());
 
                String key = keyOf(node);
                Integer recordedG = bestGMap.get(key);
                // 仅当找到更小的代价时才更新与入Open,避免等价代价反复入队导致父链抖动
                if (recordedG == null || node.getG() < recordedG) {
                    bestGMap.put(key, node.getG());
 
                    Open.add(node);
                }
            }
        }
        //如果遍历完所有出现的结点都没有找到最终的结点,返回null
        return null;
    }
 
    public List<List<NavigateNode>> allSimplePaths(
            List<List<NavigateNode>> map,
            NavigateNode start,
            NavigateNode end,
            int maxDepth,    // 最大步数(边数). 建议:50/100/200;<=0 表示不限制(不建议)
            int maxPaths,    // 最大返回条数. 建议:100/500/2000;<=0 表示不限制(不建议)
            int maxCost      // 最大总代价(含拐点惩罚). <=0 表示不限制
    ) {
        return allSimplePaths(map, start, end, maxDepth, maxPaths, maxCost, Collections.emptyList());
    }
 
    public List<List<NavigateNode>> allSimplePaths(
            List<List<NavigateNode>> map,
            NavigateNode start,
            NavigateNode end,
            int maxDepth,
            int maxPaths,
            int maxCost,
            List<Integer> guideStationIds
    ) {
        List<List<NavigateNode>> results = new ArrayList<>();
        if (map == null || map.isEmpty() || map.get(0).isEmpty()) return results;
        if (start == null || end == null) return results;
        if (start.getValue() == MapNodeType.DISABLE.id || end.getValue() == MapNodeType.DISABLE.id) return results;
 
        // visited 用坐标 key,避免 NavigateNode equals/hashCode 不可靠导致重复判断失效
        Set<String> visited = new HashSet<>(map.size() * map.get(0).size() * 2);
        LinkedList<NavigateNode> path = new LinkedList<>();
 
        String startKey = keyOf(start);
        visited.add(startKey);
        path.add(start);
 
        AtomicInteger pathCount = new AtomicInteger(0);
        Map<Integer, NavigateNode> guideNodeMap = buildGuideNodeMap(map, guideStationIds);
 
        dfsAllSimplePaths(map, start, end,
                visited, path, results,
                0,  // depth
                0,  // cost
                maxDepth, maxPaths, maxCost,
                pathCount,
                guideStationIds,
                guideNodeMap
        );
 
        return results;
    }
 
    /**
     * DFS + 回溯:枚举所有简单路径(路径中不允许重复节点)
     */
    private void dfsAllSimplePaths(
            List<List<NavigateNode>> map,
            NavigateNode current,
            NavigateNode end,
            Set<String> visited,
            LinkedList<NavigateNode> path,
            List<List<NavigateNode>> results,
            int depth,     // 当前步数(边数)
            int cost,      // 当前总代价(你可以认为是 g)
            int maxDepth,
            int maxPaths,
            int maxCost,
            AtomicInteger pathCount,
            List<Integer> guideStationIds,
            Map<Integer, NavigateNode> guideNodeMap
    ) {
        // 防爆:条数限制
        if (maxPaths > 0 && pathCount.get() >= maxPaths) return;
 
        // 到达终点:收集路径
        if (current.getX() == end.getX() && current.getY() == end.getY()) {
            results.add(new ArrayList<>(path));
            pathCount.incrementAndGet();
            return;
        }
 
        // 防爆:深度限制(depth 表示已走的边数)
        if (maxDepth > 0 && depth >= maxDepth) return;
 
        // 扩展邻居(严格复用你自己的可行走方向规则)
        ArrayList<NavigateNode> neighbors = extend_current_node(map, current);
        if (neighbors == null || neighbors.isEmpty()) return;
        neighbors = sortNeighborsByGuide(current, path, neighbors, guideStationIds, guideNodeMap);
 
        for (NavigateNode next : neighbors) {
            // 防爆:条数限制
            if (maxPaths > 0 && pathCount.get() >= maxPaths) return;
 
            if (next == null) continue;
            if (next.getValue() == MapNodeType.DISABLE.id) continue;
 
            String nk = keyOf(next);
 
            // 简单路径:不允许重复节点
            if (visited.contains(nk)) continue;
 
            // 你的代价规则:每步 1 + 拐点惩罚
            int stepCost = 1 + calcNodeExtraCost(current, next, end);
            int newCost = cost + stepCost;
 
            // 防爆:总代价限制
            if (maxCost > 0 && newCost > maxCost) continue;
 
            // 进入
            visited.add(nk);
            path.addLast(next);
 
            dfsAllSimplePaths(map, next, end,
                    visited, path, results,
                    depth + 1,
                    newCost,
                    maxDepth, maxPaths, maxCost,
                    pathCount,
                    guideStationIds,
                    guideNodeMap
            );
 
            // 回溯
            path.removeLast();
            visited.remove(nk);
        }
    }
 
    private String keyOf(NavigateNode n) {
        return n.getX() + "_" + n.getY();
    }
 
    private Map<Integer, NavigateNode> buildGuideNodeMap(List<List<NavigateNode>> map, List<Integer> guideStationIds) {
        Map<Integer, NavigateNode> guideNodeMap = new HashMap<>();
        if (map == null || map.isEmpty() || guideStationIds == null || guideStationIds.isEmpty()) {
            return guideNodeMap;
        }
        for (Integer stationId : guideStationIds) {
            if (stationId == null || guideNodeMap.containsKey(stationId)) {
                continue;
            }
            NavigateNode stationNode = findStationNavigateNode(map, stationId);
            if (stationNode != null) {
                guideNodeMap.put(stationId, stationNode);
            }
        }
        return guideNodeMap;
    }
 
    private ArrayList<NavigateNode> sortNeighborsByGuide(NavigateNode current,
                                                         LinkedList<NavigateNode> path,
                                                         ArrayList<NavigateNode> neighbors,
                                                         List<Integer> guideStationIds,
                                                         Map<Integer, NavigateNode> guideNodeMap) {
        if (current == null || neighbors == null || neighbors.size() <= 1
                || guideStationIds == null || guideStationIds.isEmpty()
                || guideNodeMap == null || guideNodeMap.isEmpty()) {
            return neighbors;
        }
 
        Integer nextGuideStationId = resolveNextGuideStationId(path, guideStationIds);
        if (nextGuideStationId == null) {
            return neighbors;
        }
        NavigateNode guideTargetNode = guideNodeMap.get(nextGuideStationId);
        if (guideTargetNode == null) {
            return neighbors;
        }
 
        neighbors.sort((left, right) -> compareGuideNeighbor(current, left, right, nextGuideStationId, guideTargetNode));
        return neighbors;
    }
 
    private Integer resolveNextGuideStationId(LinkedList<NavigateNode> path, List<Integer> guideStationIds) {
        if (path == null || path.isEmpty() || guideStationIds == null || guideStationIds.isEmpty()) {
            return null;
        }
 
        int cursor = 0;
        Set<Integer> seen = new HashSet<>();
        for (NavigateNode node : path) {
            Integer stationId = extractStationId(node);
            if (stationId == null || !seen.add(stationId)) {
                continue;
            }
            if (cursor < guideStationIds.size() && stationId.equals(guideStationIds.get(cursor))) {
                cursor++;
            }
        }
        if (cursor >= guideStationIds.size()) {
            return null;
        }
        return guideStationIds.get(cursor);
    }
 
    private int compareGuideNeighbor(NavigateNode current,
                                     NavigateNode left,
                                     NavigateNode right,
                                     Integer nextGuideStationId,
                                     NavigateNode guideTargetNode) {
        int leftDirect = isGuideStation(left, nextGuideStationId) ? 0 : 1;
        int rightDirect = isGuideStation(right, nextGuideStationId) ? 0 : 1;
        if (leftDirect != rightDirect) {
            return Integer.compare(leftDirect, rightDirect);
        }
 
        int leftDistance = calcNodeCost(left, guideTargetNode);
        int rightDistance = calcNodeCost(right, guideTargetNode);
        if (leftDistance != rightDistance) {
            return Integer.compare(leftDistance, rightDistance);
        }
 
        int leftTurnCost = calcNodeExtraCost(current, left, guideTargetNode);
        int rightTurnCost = calcNodeExtraCost(current, right, guideTargetNode);
        if (leftTurnCost != rightTurnCost) {
            return Integer.compare(leftTurnCost, rightTurnCost);
        }
 
        return 0;
    }
 
    private boolean isGuideStation(NavigateNode node, Integer stationId) {
        Integer nodeStationId = extractStationId(node);
        return nodeStationId != null && nodeStationId.equals(stationId);
    }
 
    private Integer extractStationId(NavigateNode node) {
        if (node == null) {
            return null;
        }
        if (node.getStationId() != null) {
            return node.getStationId();
        }
        applyNodeMetadata(node);
        return node.getStationId();
    }
 
    private JSONObject parseNodeValue(String nodeValue) {
        if (nodeValue == null || nodeValue.trim().isEmpty()) {
            return null;
        }
        try {
            return JSON.parseObject(nodeValue);
        } catch (Exception ignore) {
            return null;
        }
    }
 
    public ArrayList<NavigateNode> extend_current_node(List<List<NavigateNode>> map, NavigateNode current_node) {
        //获取当前结点的x, y
        int x = current_node.getX();
        int y = current_node.getY();
        //如果当前结点的邻结点合法,就加入到neighbour_node
        ArrayList<NavigateNode> neighbour_node = new ArrayList<NavigateNode>();
 
        if(current_node.getValue() == MapNodeType.DISABLE.id) {
            return neighbour_node;
        }
 
        List<String> directionList = current_node.getDirectionList();
        if(directionList == null || directionList.size() == 0) {
            return neighbour_node;
        }
 
        for(String direction : directionList) {
            if(direction.equals("top")) {
                NavigateNode node = getValidNavigateNode(map, current_node, x - 1, y, direction);
                if(node != null) {
                    neighbour_node.add(node);
                }
            }else if(direction.equals("bottom")) {
                NavigateNode node = getValidNavigateNode(map, current_node, x + 1, y, direction);
                if(node != null) {
                    neighbour_node.add(node);
                }
            }else if(direction.equals("left")) {
                NavigateNode node = getValidNavigateNode(map, current_node, x, y - 1, direction);
                if(node != null) {
                    neighbour_node.add(node);
                }
            }else if(direction.equals("right")) {
                NavigateNode node = getValidNavigateNode(map, current_node, x, y + 1, direction);
                if(node != null) {
                    neighbour_node.add(node);
                }
            }
        }
 
        return neighbour_node;
    }
 
    /**
     * 邻接点校验:可达 + 方向一致(当前节点与下一节点对本次行走方向一致)
     */
    public NavigateNode getValidNavigateNode(List<List<NavigateNode>> map, NavigateNode currentNode, int x, int y, String moveDirection) {
        NavigateNode node = getValidNavigateNode(map, x, y);
        if (node == null) {
            return null;
        }
 
        if (!isDirectionConsistent(currentNode, node, moveDirection)) {
            return null;
        }
 
        return node;
    }
 
    public NavigateNode getValidNavigateNode(List<List<NavigateNode>> map, int x, int y) {
        if (x < 0 || x >= map.size()
                || y < 0 || y >= map.get(0).size()) {
            return null;
        }
 
        NavigateNode node = map.get(x).get(y);
        if(node.getValue() == MapNodeType.DISABLE.id) {
            return null;
        }
 
        return node;
    }
 
    private boolean isDirectionConsistent(NavigateNode currentNode, NavigateNode nextNode, String moveDirection) {
        if (currentNode == null || nextNode == null) {
            return false;
        }
 
        if (moveDirection == null) {
            return false;
        }
 
        List<String> currentDirectionList = currentNode.getDirectionList();
        List<String> nextDirectionList = nextNode.getDirectionList();
        if (currentDirectionList == null || nextDirectionList == null) {
            return false;
        }
 
        // 当前节点允许向 moveDirection 出发,且下一节点在该方向上保持一致,才允许通行
        return currentDirectionList.contains(moveDirection) && nextDirectionList.contains(moveDirection);
    }
 
    public NavigateNode findStationNavigateNode(List<List<NavigateNode>> map, int stationId) {
        NavigateNode bestNode = null;
        int bestExternalConnectionCount = -1;
        int bestNeighborCount = -1;
        for(int x = 0; x < map.size(); x++) {
            for(int y = 0; y < map.get(0).size(); y++) {
                NavigateNode node = map.get(x).get(y);
                Integer currentStationId = extractStationId(node);
                if (currentStationId == null || currentStationId != stationId) {
                    continue;
                }
                ArrayList<NavigateNode> neighbors = extend_current_node(map, node);
                int externalConnectionCount = countExternalConnectionCount(stationId, neighbors);
                int neighborCount = neighbors == null ? 0 : neighbors.size();
                if (externalConnectionCount > bestExternalConnectionCount
                        || (externalConnectionCount == bestExternalConnectionCount && neighborCount > bestNeighborCount)) {
                    bestNode = node;
                    bestExternalConnectionCount = externalConnectionCount;
                    bestNeighborCount = neighborCount;
                }
            }
        }
        return bestNode;
    }
 
    public NavigateNode findStationNavigateNode(NavigateMapIndex navigateMapIndex, int stationId) {
        if (navigateMapIndex == null) {
            return null;
        }
        return navigateMapIndex.getBestStationNode(stationId);
    }
 
    private int countExternalConnectionCount(Integer currentStationId, List<NavigateNode> neighbors) {
        Set<Integer> connectedStationIdSet = new LinkedHashSet<>();
        if (neighbors == null || neighbors.isEmpty()) {
            return 0;
        }
        for (NavigateNode neighbor : neighbors) {
            connectedStationIdSet.addAll(resolveAdjacentStationIds(currentStationId, neighbor));
        }
        return connectedStationIdSet.size();
    }
 
    private Set<Integer> resolveAdjacentStationIds(Integer currentStationId, NavigateNode node) {
        Set<Integer> stationIdSet = new LinkedHashSet<>();
        if (node == null) {
            return stationIdSet;
        }
        Integer directStationId = extractStationId(node);
        if (directStationId != null && !directStationId.equals(currentStationId)) {
            stationIdSet.add(directStationId);
        }
        for (Integer bridgeStationId : node.getBridgeStationIds() == null ? Collections.<Integer>emptyList() : node.getBridgeStationIds()) {
            if (bridgeStationId != null && !bridgeStationId.equals(currentStationId)) {
                stationIdSet.add(bridgeStationId);
            }
        }
        return stationIdSet;
    }
 
    public List<NavigateNode> getNeighborNodes(NavigateMapIndex navigateMapIndex, NavigateNode node) {
        if (navigateMapIndex == null || node == null) {
            return Collections.emptyList();
        }
        return navigateMapIndex.getNeighborNodes(node);
    }
 
    public Set<Integer> getConnectedStationIds(NavigateMapIndex navigateMapIndex,
                                               Integer currentStationId,
                                               NavigateNode node) {
        if (navigateMapIndex == null || node == null) {
            return Collections.emptySet();
        }
        return navigateMapIndex.getConnectedStationIds(currentStationId, node);
    }
 
    private NavigateMapIndex buildNavigateMapIndex(int lev, List<List<NavigateNode>> navigateMap) {
        if (navigateMap == null || navigateMap.isEmpty()) {
            return new NavigateMapIndex(lev,
                    new ArrayList<>(),
                    Collections.emptyMap(),
                    Collections.emptyMap(),
                    Collections.emptyMap(),
                    Collections.emptyMap());
        }
 
        enrichNavigateMapMetadata(navigateMap);
        Map<String, NavigateNodeMeta> nodeMetaMap = new LinkedHashMap<>();
        Map<String, List<NavigateNode>> neighborNodeMap = new LinkedHashMap<>();
        Map<String, Set<Integer>> connectedStationIdMap = new LinkedHashMap<>();
 
        for (List<NavigateNode> row : navigateMap) {
            for (NavigateNode node : row) {
                if (node == null || node.getValue() == MapNodeType.DISABLE.id) {
                    continue;
                }
                String nodeKey = buildNodeKey(node);
                nodeMetaMap.put(nodeKey, buildNavigateNodeMeta(node));
                List<NavigateNode> neighborList = extend_current_node(navigateMap, node);
                neighborNodeMap.put(nodeKey, Collections.unmodifiableList(new ArrayList<>(neighborList)));
            }
        }
 
        Map<Integer, NavigateNode> stationNodeMap = new LinkedHashMap<>();
        Map<Integer, Integer> stationExternalCountMap = new HashMap<>();
        Map<Integer, Integer> stationNeighborCountMap = new HashMap<>();
        for (List<NavigateNode> row : navigateMap) {
            for (NavigateNode node : row) {
                if (node == null || node.getValue() == MapNodeType.DISABLE.id) {
                    continue;
                }
                String nodeKey = buildNodeKey(node);
                Integer stationId = extractStationId(node);
                Set<Integer> connectedStationIds = resolveAdjacentStationIds(stationId, neighborNodeMap.get(nodeKey));
                connectedStationIdMap.put(nodeKey, Collections.unmodifiableSet(connectedStationIds));
                if (stationId == null) {
                    continue;
                }
                int externalConnectionCount = connectedStationIds.size();
                int neighborCount = neighborNodeMap.get(nodeKey).size();
                Integer bestExternalCount = stationExternalCountMap.get(stationId);
                Integer bestNeighborCount = stationNeighborCountMap.get(stationId);
                if (bestExternalCount == null
                        || externalConnectionCount > bestExternalCount
                        || (externalConnectionCount == bestExternalCount && (bestNeighborCount == null || neighborCount > bestNeighborCount))) {
                    stationNodeMap.put(stationId, node);
                    stationExternalCountMap.put(stationId, externalConnectionCount);
                    stationNeighborCountMap.put(stationId, neighborCount);
                }
            }
        }
        return new NavigateMapIndex(lev,
                navigateMap,
                Collections.unmodifiableMap(nodeMetaMap),
                Collections.unmodifiableMap(stationNodeMap),
                Collections.unmodifiableMap(neighborNodeMap),
                Collections.unmodifiableMap(connectedStationIdMap));
    }
 
    private Set<Integer> resolveAdjacentStationIds(Integer currentStationId, List<NavigateNode> neighbors) {
        Set<Integer> connectedStationIdSet = new LinkedHashSet<>();
        if (neighbors == null || neighbors.isEmpty()) {
            return connectedStationIdSet;
        }
        for (NavigateNode neighbor : neighbors) {
            connectedStationIdSet.addAll(resolveAdjacentStationIds(currentStationId, neighbor));
        }
        return connectedStationIdSet;
    }
 
    private String buildNodeKey(NavigateNode node) {
        if (node == null) {
            return "";
        }
        return node.getX() + "_" + node.getY();
    }
 
    private NavigateNodeMeta buildNavigateNodeMeta(NavigateNode node) {
        return new NavigateNodeMeta(
                extractStationId(node),
                node == null || node.getBridgeStationIds() == null ? Collections.emptyList() : node.getBridgeStationIds(),
                node != null && Boolean.TRUE.equals(node.getLiftTransfer()),
                node != null && Boolean.TRUE.equals(node.getRgvCalcFlag())
        );
    }
 
    public NavigateNode findTrackSiteNoNavigateNode(List<List<NavigateNode>> map, int trackSiteNo) {
        for(int x = 0; x < map.size(); x++) {
            for(int y = 0; y < map.get(0).size(); y++) {
                NavigateNode node = map.get(x).get(y);
                if("rgv".equals(node.getNodeType())) {
                    JSONObject valueObj = JSON.parseObject(node.getNodeValue());
                    if(valueObj.getInteger("trackSiteNo") == trackSiteNo) {
                        return node;
                    }
                }
            }
        }
        return null;
    }
 
    //------------------A*启发函数------------------//
 
    //计算通过现在的结点的位置和最终结点的位置计算H值(曼哈顿法:坐标分别取差值相加)
    private int calcNodeCost(NavigateNode node1, NavigateNode node2) {
        return Math.abs(node2.getX() - node1.getX()) + Math.abs(node2.getY() - node1.getY());
    }
 
    //去除拐点算法,给直线增加优先级
    private int calcNodeExtraCost(NavigateNode currNode, NavigateNode nextNode, NavigateNode endNode) {
        // 第一个点或直线点
        if (currNode.getFather() == null || nextNode.getX() == currNode.getFather().getX()
                || nextNode.getY() == currNode.getFather().getY()) {
            return 0;
        }
 
        // 拐向终点的点
        if (nextNode.getX() == endNode.getX() || nextNode.getY() == endNode.getY()) {
            return 1;
        }
 
        // 普通拐点
        /*
        拐点判断逻辑
        拿到父节点和下一节点
        通过判断父节点和下一节点的x数据和y数据都不相同时,则表明当前坐标是一个拐点
         */
        return 1;
    }
 
    //------------------A*启发函数-end------------------//
 
    public static class NavigateMapIndex {
        private final int lev;
        private final List<List<NavigateNode>> navigateMap;
        private final Map<String, NavigateNodeMeta> nodeMetaMap;
        private final Map<Integer, NavigateNode> stationNodeMap;
        private final Map<String, List<NavigateNode>> neighborNodeMap;
        private final Map<String, Set<Integer>> connectedStationIdMap;
 
        private NavigateMapIndex(int lev,
                                 List<List<NavigateNode>> navigateMap,
                                 Map<String, NavigateNodeMeta> nodeMetaMap,
                                 Map<Integer, NavigateNode> stationNodeMap,
                                 Map<String, List<NavigateNode>> neighborNodeMap,
                                 Map<String, Set<Integer>> connectedStationIdMap) {
            this.lev = lev;
            this.navigateMap = navigateMap == null ? new ArrayList<>() : navigateMap;
            this.nodeMetaMap = nodeMetaMap == null ? Collections.emptyMap() : nodeMetaMap;
            this.stationNodeMap = stationNodeMap == null ? Collections.emptyMap() : stationNodeMap;
            this.neighborNodeMap = neighborNodeMap == null ? Collections.emptyMap() : neighborNodeMap;
            this.connectedStationIdMap = connectedStationIdMap == null ? Collections.emptyMap() : connectedStationIdMap;
        }
 
        public int getLev() {
            return lev;
        }
 
        public List<List<NavigateNode>> getNavigateMap() {
            return navigateMap;
        }
 
        public NavigateNode getBestStationNode(Integer stationId) {
            if (stationId == null) {
                return null;
            }
            return stationNodeMap.get(stationId);
        }
 
        public List<NavigateNode> getNeighborNodes(NavigateNode node) {
            if (node == null) {
                return Collections.emptyList();
            }
            return neighborNodeMap.getOrDefault(node.getX() + "_" + node.getY(), Collections.emptyList());
        }
 
        public Set<Integer> getConnectedStationIds(Integer currentStationId, NavigateNode node) {
            if (node == null) {
                return Collections.emptySet();
            }
            Set<Integer> stationIdSet = connectedStationIdMap.getOrDefault(node.getX() + "_" + node.getY(), Collections.emptySet());
            if (currentStationId == null || stationIdSet.isEmpty()) {
                return stationIdSet;
            }
            if (!stationIdSet.contains(currentStationId)) {
                return stationIdSet;
            }
            Set<Integer> filterStationIdSet = new LinkedHashSet<>();
            for (Integer stationId : stationIdSet) {
                if (stationId != null && !stationId.equals(currentStationId)) {
                    filterStationIdSet.add(stationId);
                }
            }
            return filterStationIdSet;
        }
 
        public Integer getStationId(NavigateNode node) {
            NavigateNodeMeta meta = getNodeMeta(node);
            return meta == null ? null : meta.stationId;
        }
 
        public List<Integer> getBridgeStationIds(NavigateNode node) {
            NavigateNodeMeta meta = getNodeMeta(node);
            return meta == null ? Collections.emptyList() : meta.bridgeStationIds;
        }
 
        public boolean isLiftTransfer(NavigateNode node) {
            NavigateNodeMeta meta = getNodeMeta(node);
            return meta != null && meta.liftTransfer;
        }
 
        public boolean isRgvCalcFlag(NavigateNode node) {
            NavigateNodeMeta meta = getNodeMeta(node);
            return meta != null && meta.rgvCalcFlag;
        }
 
        private NavigateNodeMeta getNodeMeta(NavigateNode node) {
            if (node == null) {
                return null;
            }
            return nodeMetaMap.get(node.getX() + "_" + node.getY());
        }
    }
 
    private static class NavigateNodeMeta {
        private final Integer stationId;
        private final List<Integer> bridgeStationIds;
        private final boolean liftTransfer;
        private final boolean rgvCalcFlag;
 
        private NavigateNodeMeta(Integer stationId,
                                 List<Integer> bridgeStationIds,
                                 boolean liftTransfer,
                                 boolean rgvCalcFlag) {
            this.stationId = stationId;
            this.bridgeStationIds = bridgeStationIds == null ? Collections.emptyList() : bridgeStationIds;
            this.liftTransfer = liftTransfer;
            this.rgvCalcFlag = rgvCalcFlag;
        }
    }
 
    private static class CachedNavigateMap {
        private final long cacheAtMs;
        private final List<List<NavigateNode>> navigateMap;
 
        private CachedNavigateMap(long cacheAtMs, List<List<NavigateNode>> navigateMap) {
            this.cacheAtMs = cacheAtMs;
            this.navigateMap = navigateMap;
        }
    }
 
    private static class CachedNavigateMapIndex {
        private final long cacheAtMs;
        private final NavigateMapIndex navigateMapIndex;
 
        private CachedNavigateMapIndex(long cacheAtMs, NavigateMapIndex navigateMapIndex) {
            this.cacheAtMs = cacheAtMs;
            this.navigateMapIndex = navigateMapIndex;
        }
    }
}