单点最短路径
概念:给定一幅图和一个起点s,回答"从s到给定目的顶点v是否存在一条路径",如果有找出最短的那一条(所含边数最少)等类似的问题
import java.util.*;
//以一个实际的图案例来使用广度优先搜索查找图中的路径(路径最短)
public class test1 {
static int n = 6;
static int[] edgeTo = new int[n];
static int[][] map = new int[n][n];
static boolean[] vis = new boolean[n];
static int s = 0;//起点
static Scanner in = new Scanner(System.in);
//初始化图
static void init()
{
for(int i=0;i<n;i++)
{
Arrays.fill(map[i],0);
}
map[0][1]=map[1][0]=1;
map[0][2]=map[2][0]=1;
map[1][2]=map[2][1]=1;
map[0][5]=map[5][0]=1;
map[3][5]=map[5][3]=1;
map[3][2]=map[2][3]=1;
map[3][4]=map[4][3]=1;
map[2][4]=map[4][2]=1;
}
static void bfs(int v)
{
Queue<Integer> q = new LinkedList<>();
vis[v] = true;//标记起点
q.add(v);//将它加入队列
while(!q.isEmpty())
{
int temp = q.peek();
q.poll();//从队列中删去下一个顶点
for(int i=0;i<n;i++)
{
if(!vis[i]&&map[temp][i]==1)
{
vis[i] = true;//标记
q.add(i);//加入队列
edgeTo[i] = temp;//保存最短路径最后一条边
}
}
}
}
static boolean hasPathTo(int v)
{
return vis[v];
}
static Stack<Integer> pathTo(int v)
{
if(!hasPathTo(v)) return null;
Stack<Integer> path = new Stack<>();
for(int x = v;x!=s;x = edgeTo[x])
{
path.push(x);
}
path.push(s);
return path;
}
public static void main(String[] args) {
init();
bfs(0);
Stack<Integer> path = pathTo(4);
while(!path.isEmpty())
{
int w = path.pop();
System.out.print(w + "->");
}
}
}