#
Junjie
1 天以前 3372040097ad2c01aeb6fd6485e89f19bf81b316
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
package com.zy.common.utils;
 
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
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.MapNodeType;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
 
/**
 * A*算法实现类
 */
public class NavigateSolution {
 
    // Open表用优先队列
    public PriorityQueue<NavigateNode> Open = new PriorityQueue<NavigateNode>();
    //Close表用普通的数组
    public ArrayList<NavigateNode> Close = new ArrayList<NavigateNode>();
    //用来存放已经出现过的结点。
    Map<String, Integer> bestGMap = new HashMap<>();
 
    public List<List<NavigateNode>> getStationMap(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 mergeType = map.getString("mergeType");
                String nodeType = map.getString("type");
                String nodeValue = map.getString("value");
                if(nodeType == null) {
                    navigateNode.setValue(MapNodeType.DISABLE.id);
                }else if(nodeType.equals("devp") || (nodeType.equals("merge") && mergeType.equals("devp"))) {
                    navigateNode.setValue(MapNodeType.NORMAL_PATH.id);
 
                    JSONObject valueObj = JSON.parseObject(map.getString("value"));
                    List<String> directionList = valueObj.getJSONArray("direction").toJavaList(String.class);
                    navigateNode.setDirectionList(directionList);
                } else if (nodeType.equals("rgv")) {
                    navigateNode.setValue(MapNodeType.NORMAL_PATH.id);
                    JSONObject valueObj = JSON.parseObject(map.getString("value"));
 
                    JSONObject newNodeValue = new JSONObject();
                    newNodeValue.put("rgvCalcFlag", 1);
                    nodeValue = JSON.toJSONString(newNodeValue);
 
                    //RGV暂不控制行走方向,默认上下左右都可走
                    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);
                navigateNodeRow.add(navigateNode);
            }
            navigateNodeList.add(navigateNodeRow);
        }
 
        return navigateNodeList;
    }
 
    public List<List<NavigateNode>> getRgvTrackMap(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");
                if(nodeType == null) {
                    navigateNode.setValue(MapNodeType.DISABLE.id);
                }else if(nodeType.equals("rgv")){
                    navigateNode.setValue(MapNodeType.NORMAL_PATH.id);
                    JSONObject valueObj = JSON.parseObject(map.getString("value"));
 
                    //RGV暂不控制行走方向,默认上下左右都可走
                    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(map.getString("value"));
                navigateNodeRow.add(navigateNode);
            }
            navigateNodeList.add(navigateNodeRow);
        }
 
        return navigateNodeList;
    }
 
    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(current_node);
            //对当前结点进行扩展,得到一个四周结点的数组
            ArrayList<NavigateNode> neighbour_node = extend_current_node(map, current_node);
            //对这个结点遍历,看是否有目标结点出现
            for (NavigateNode node : neighbour_node) {
                // 已在关闭列表中的节点不再处理,避免父链反复改写形成环
                if (Close.contains(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 = node.getX() + "_" + node.getY();
                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 || !"devp".equals(node.getNodeType())) {
            return null;
        }
        try {
            JSONObject valueObj = JSON.parseObject(node.getNodeValue());
            return valueObj == null ? null : valueObj.getInteger("stationId");
        } 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) {
        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("devp".equals(node.getNodeType())) {
                    JSONObject valueObj = JSON.parseObject(node.getNodeValue());
                    if(valueObj.getInteger("stationId") == stationId) {
                        return node;
                    }
                }
            }
        }
        return null;
    }
 
    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------------------//
 
}