Android应用中经常需要求最短路径,需要用到实现该功能的迪杰斯特拉(Dijkstra)算法,在网上找到了该算法的实现方法,并做了简单的修改,应用到了Android的程序中进行了测试,下面附上测试代码和图片:
布局(activity_main.xml):
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<EditText
android:id="@+id/et_point"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_weight="1.27"/>
<Button
android:id="@+id/btn_add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="添加点" />
<Button
android:id="@+id/btn_ok"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="路径规划" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="点:" />
<Button
android:id="@+id/btn_reset"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="重置数据" />
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<TextView
android:id="@+id/textView2"
android:layout_width="match_parent"
android:layout_height="348dp"
android:background="@drawable/test_map"
/>
</FrameLayout>
</LinearLayout>
</LinearLayout>
新建Dijkstra2类:
package com.example.dijkstra_test2;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
public class Dijkstra2 {
public static int INFINITY = 99999;
public static Map<String, Vertex> vertexMap = new HashMap<String, Vertex>();
// 边距
static class Edge {
public Vertex dest;
public double cost;
public Edge(Vertex d, double c) {
this.dest = d;
this.cost = c;
}
}
// 静态类:Vertex
static class Vertex implements Comparable<Vertex> {
public String name;
public List<Edge> adj;
public double dist;
public Vertex prev;
public int scratch;
public boolean visited;
public Vertex(String nm) {
this.name = nm;
adj = new ArrayList<Edge>();
reset();
}
public void reset() {
visited = false;
dist = Dijkstra2.INFINITY;
}
@Override
public int compareTo(Vertex o) {
double c = o.dist;
return dist < c ? -1 : dist > c ? 1 : 0;
}
}
// Dijkstra算法实现:找到从startName点出发,到其他所有点的最短路径:选取自己定义的终点
public static String dijkstra(String startName, String endName) {
PriorityQueue<Vertex> pq = new PriorityQueue<Vertex>();// 该队列以权值升序排列,因为Vertex实现Comparable接口
Vertex start = vertexMap.get(startName);
start.dist = 0;
for (Vertex v : vertexMap.values())
pq.add(v);
int seenNum = 0;
while (!pq.isEmpty() && seenNum < vertexMap.size()) {
Vertex v = pq.remove();
if (v.name.equals(endName)) { // 恰好是自己要找的那个点
System.out.println(startName + "---->" + v.name + ":" + v.dist); // 最短距离
System.out.println(getPreNames(v)); // 最短路线
return startName + "---->" + v.name + ":" + v.dist + "\r\n"
+ getPreNames(v)+ "\r\n";
}
if (v.scratch != 0)
continue;
v.scratch = 1;
seenNum++;
for (Edge e : v.adj) {
Vertex w = e.dest;
double v_to_w = e.cost;
if (w.dist > v.dist + v_to_w) {
w.dist = v.dist + v_to_w;
w.prev = v;
pq.remove(w);// 出队
pq.add(w);// 按优先级插在队头,先插入的在队头,依次往后
}
}
}
System.out.println("hello!");
while (pq.peek() != null) {
System.out.println(pq.poll());
return pq.poll().toString();
}
return "";
}
/**
* 得到最短路径所经历的路线 seven
*
* @param v
* @return
*/
public static String getPreNames(Vertex v) {
String routeEndName = v.name;
StringBuilder sb = new StringBuilder();
while (v.prev != null) {
sb.append(v.prev.name + ",");
v = v.prev;
}
String reverseRoute = routeEndName + "," + sb.toString();
String[] reverseArray = reverseRoute.split(",");
StringBuilder route = new StringBuilder();
for (int i = 0; i < reverseArray.length; i++) {
route.append(reverseArray[reverseArray.length - 1 - i]);
route.append(",");
}
return route.substring(0, route.length() - 1);
}
}
新建activity(MainAvtivity)类:
package com.example.dijkstra_test2;
import java.util.List;
import com.example.dijkstra_test2.Dijkstra2.*;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
public class MainActivity extends Activity {
private Button btn_ok;
private Button btn_add;
private Button btn_reset;
private EditText et_point;
private TextView tv_point;
private String path = "";
private String point[] = new String[9];
private int i = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_add = (Button) findViewById(R.id.btn_add);
btn_ok = (Button) findViewById(R.id.btn_ok);
btn_reset = (Button) findViewById(R.id.btn_reset);
et_point = (EditText) findViewById(R.id.et_point);
tv_point = (TextView) findViewById(R.id.textView1);
btn_add.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO 自动生成的方法存根
if (et_point.getText() == null
|| et_point.getText().toString() == "") {
btn_add.setClickable(false);
}
if (i == 9) {
btn_add.setClickable(false);
btn_add.setText("到达点数上限");
}
point[i] = et_point.getText().toString();
tv_point.setText(tv_point.getText().toString() + point[i]
+ ",,");
i++;
et_point.setText("");
}
});
btn_ok.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
for (int j = 1; j < i; j++) {
path += dijkstra(point[j - 1], point[j]);
}
tv_point.setText(path);
}
});
btn_reset.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO 自动生成的方法存根
Intent intent = getIntent();
finish();
startActivity(intent);
}
});
}
public String dijkstra(String p1, String p2) {
// 构建有向图
Vertex v1 = new Vertex("a");//建点
Vertex v2 = new Vertex("b");
Vertex v3 = new Vertex("c");
Vertex v4 = new Vertex("d");
Vertex v5 = new Vertex("e");
List<Edge> e1l = v1.adj;//建边
List<Edge> e2l = v2.adj;
List<Edge> e3l = v3.adj;
List<Edge> e4l = v4.adj;
List<Edge> e5l=v5.adj;
Edge e12 = new Edge(v2, 45);赋值边
Edge e13 = new Edge(v3, 30);
Edge e15 = new Edge(v5, 50);
e1l.add(e13);
e1l.add(e15);
e1l.add(e12);
Edge e24 = new Edge(v4, 60);
Edge e21 = new Edge(v1, 45);
e2l.add(e24);
e2l.add(e21);
Edge e35 = new Edge(v5, 45);
e3l.add(e35);
Edge e31 = new Edge(v1, 30);
e3l.add(e31);
Edge e45 = new Edge(v5, 55);
e4l.add(e45);
Edge e42 = new Edge(v2, 60);
e4l.add(e42);
Edge e51=new Edge(v1, 50);
Edge e53=new Edge(v3, 45);
Edge e54=new Edge(v4, 55);
e5l.add(e51);
e5l.add(e54);
e5l.add(e53);
// 构建有向图完毕
Dijkstra2.vertexMap.put("a", v1);
Dijkstra2.vertexMap.put("b", v2);
Dijkstra2.vertexMap.put("c", v3);
Dijkstra2.vertexMap.put("d", v4);
Dijkstra2.vertexMap.put("e", v5);
return Dijkstra2.dijkstra(p1, p2);
}
}
效果图:
下面附上drawable文件: