结队作业-地铁查询作业(5)
建立SQLite数据库
java Copy code public class DatabaseHelper extends SQLiteOpenHelper { private static final String DATABASE_NAME = "subway.db"; private static final int DATABASE_VERSION = 1; public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE stations (_id INTEGER PRIMARY KEY, name TEXT NOT NULL, line_id INTEGER NOT NULL);"); db.execSQL("CREATE TABLE lines (_id INTEGER PRIMARY KEY, name TEXT NOT NULL, color TEXT NOT NULL);"); db.execSQL("CREATE TABLE station_lines (_id INTEGER PRIMARY KEY, station_id INTEGER NOT NULL, line_id INTEGER NOT NULL, FOREIGN KEY (station_id) REFERENCES stations (_id), FOREIGN KEY (line_id) REFERENCES lines (_id));"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS stations;"); db.execSQL("DROP TABLE IF EXISTS lines;"); db.execSQL("DROP TABLE IF EXISTS station_lines;"); onCreate(db); } }
查询路径
java Copy code public class PathFinder { private static final int INFINITY = Integer.MAX_VALUE; private Graph graph; private int[] distTo; private boolean[] marked; private Edge[] edgeTo; private PriorityQueue<Station> pq; public PathFinder(Graph graph) { this.graph = graph; } public void findPath(Station start, Station end) { distTo = new int[graph.getNumVertices()]; marked = new boolean[graph.getNumVertices()]; edgeTo = new Edge[graph.getNumVertices()]; pq = new PriorityQueue<>(graph.getNumVertices()); for (int v = 0; v < graph.getNumVertices(); v++) { distTo[v] = INFINITY; } distTo[start.getId()] = 0; pq.add(start); while (!pq.isEmpty()) { Station v = pq.poll(); if (v == end) { break; } for (Edge e : graph.getAdjacentEdges(v)) { Station w = e.getOther(v); if (distTo[v.getId()] + e.getWeight() < distTo[w.getId()]) { distTo[w.getId()] = distTo[v.getId()] + e.getWeight(); edgeTo[w.getId()] = e; if (pq.contains(w)) { pq.remove(w); } pq.add(w); } } } } public Iterable<Edge> getPath() { List<Edge> path = new ArrayList<>(); for (Edge e = edgeTo[graph.getVertexIndex(graph.getEndStation())]; e != null; e = edgeTo[graph.getVertexIndex(e.getOther(graph.getVertex(e)))]) { path.add(e); } Collections.reverse(path); return path; } }
使用百度地图API查询路径
java Copy code public class BaiduMapPathFinder { private static final String AK = "your_ak"; private static final String ROUTE_URL = "http://api.map.baidu.com/directionlite/v1/transit?origin=%s&destination=%s&ak=%s"; private static final int TIMEOUT = 10000; public static String getRoute(String origin,
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人