地铁查询系统(后端)
后端主要是使用springboot+mybatis-plus架构搭建的,这里就只放算法那一部分的代码了。
package com.example.groupwork1.controller;
import com.example.groupwork1.entity.AdjacencyList;
import com.example.groupwork1.entity.Result;
import com.example.groupwork1.service.impl.AdjacencyListServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.*;
/**
* <p>
* 前端控制器
* </p>
*
* @author groupwork1
* @since 2024-03-26
*/
@RestController
@RequestMapping("/adjacency-list")
public class AdjacencyListController {
@Autowired
private AdjacencyListServiceImpl adjacencyListService;
@PostMapping("/list")
private Result list(@RequestBody Map<String, Integer> form)
{
int id1 = form.get("id1");
int id2 = form.get("id2");
Map<Integer, Integer> preStation = new HashMap<>(); // 记录每个站点的前驱节点
Map<Integer, Integer> route = new HashMap<>(); // 记录每个站点经过的线路号
bfs(id1, id2, preStation, route); // 使用BFS算法找到最短路径
List<Integer> path = new ArrayList<>();
List<Integer> route1 = new ArrayList<>();
int currentId = id2;
while (currentId != id1) {
path.add(currentId);
route1.add(route.get(currentId));
currentId = preStation.get(currentId);
}
path.add(id1);
route1.add(route.get(id1));
Collections.reverse(path); // 反转路径,使起点在前,绂点在后
Collections.reverse(route1);
Result result = new Result(path.size(), path,route1);
return result;
}
private void bfs(int startId, int endId,Map<Integer, Integer> preStation, Map<Integer, Integer> route) {
Queue<Integer> queue = new LinkedList<>();
Set<Integer> visited = new HashSet<>();
queue.offer(startId);
visited.add(startId);
while (!queue.isEmpty()) {
int currentId = queue.poll();
if (currentId == endId) {
return; // 找到终点,结束搜索
}
List<Integer> neighbors = getNeighbors(currentId); // 获取当前站点的邻居站点
for (int neighborId : neighbors) {
if (!visited.contains(neighborId)) {
queue.offer(neighborId);
visited.add(neighborId);
preStation.put(neighborId, currentId); // 记录前驱节点
route.put(neighborId, getRoute(currentId, neighborId)); // 记录经过的线路号
}
}
}
}
private List<Integer> getNeighbors(int stationId) {
List<Integer> neighbors = new ArrayList<>();
List<AdjacencyList> adjacencyList = adjacencyListService.list();
for (AdjacencyList edge : adjacencyList) {
if (edge.getFid() == stationId) {
neighbors.add(edge.getTid());
} else if (edge.getTid() == stationId) {
neighbors.add(edge.getFid());
}
}
return neighbors;
}
private int getRoute(int stationId1, int stationId2) {
List<AdjacencyList> adjacencyList = adjacencyListService.list();
for (AdjacencyList edge : adjacencyList) {
if ((edge.getFid() == stationId1 && edge.getTid() == stationId2) || (edge.getFid() == stationId2 && edge.getTid() == stationId1)) {
return edge.getLid(); // 返回线路号
}
}
return 0;
}
}

浙公网安备 33010602011771号