/** * Breadth First Search Algorithm * @param pStartPoint start point * @param pEndPoint end point * @return result */ public String BreadthFirstSearch(String pStartPoint, String pEndPoint){ // 如果起点和终点相同,则直接返回 pStartPoint pEndPoint if(Objects.equals(pStartPoint, pEndPoint)) return pStartPoint + "\t" + pEndPoint;
int[] edgeTo = newint[mSize]; boolean[] marked = newboolean[mSize]; for (int i = 0; i < mSize;i++) edgeTo[i] = -1; // 设置所有点的前驱为-1,即没有访问过
Queue<Integer> queue = new Queue<Integer>(); int startPoint = Integer.parseInt(pStartPoint) - 1; int endPoint = Integer.parseInt(pEndPoint) - 1; // 转换成计算机计数法,从0开始
marked[startPoint] = true; // 标记起点
queue.enqueue(startPoint); while (!queue.isEmpty()){ int v = queue.dequeue(); for (int i = 0; i < mSize; i++){ if(mMatrix[i][v] != 0){ if(!marked[i]){ // 如果标记了,则说明该点走过了 // 如果没有,则标记该点 edgeTo[i] = v; marked[i] = true; queue.enqueue(i); } } } } int i = endPoint; String result = ""; while (edgeTo[i] != startPoint){ if(edgeTo[i] == -1){ result = "-1\t"; break; } int num = edgeTo[i] + 1; result = num + "\t" + result; i = edgeTo[i]; } return pStartPoint + "\t" + result + pEndPoint; }
int current = startPoint; // 初始化当前点 for (int i = 1; i < mSize; i++){ // Dijkstra算法的核心操作 int min = INF; for (int j = 0; j< mSize; j++){ if(!visited[j] && distTo[j] < min){ // 寻找当前权值最小且没被访问过的点 min = distTo[j]; current = j; } } visited[current] = true; // 设置该点为当前点 for (int v = 0; v < mSize; v++){ if(mMatrix[current][v] > 0 && distTo[v] > distTo[current] + mMatrix[current][v]){ // 循环计算与当前点相邻的点 // 如果当前点加上相邻点的权小于该点的最小权值(distTo[v]) // 则覆写该点到起点的最小权值 distTo[v] = distTo[current] + mMatrix[current][v]; previous[v] = current; } } }
int i = endPoint; String result = ""; while (previous[i] != startPoint || distTo[i] == INF){ if(previous[i] == -1 || distTo[i] == INF){ result = "-1\t"; break; } int num = previous[i] + 1; result = num + "\t" + result; i = previous[i]; } return pStartPoint + "\t" + result + pEndPoint; }