学习ICTCLAS N-最短路径是很重要的一步也是非常难的一部分,学习了两天终于把它算法的大致意思通了一遍。学习N-最短路径,首先我们先看一看Dijkstra算法
它的主要思想可以简化为两部分:1)已知的最短集合路径S,未知的路径集合V-S。
2)从未知的路径V-S 中选择最短路径估计最小的U,加入S。然后对所有从U出发的边进行松弛。
具体可以参考:http://wenku.baidu.com/view/4dbd356048d7c1c708a145da.html
代码可以参考: http://wenku.baidu.com/view/f0245062783e0912a2162a11.html
下面我们来看看如何得到最短路径:
我是看了http://www.cnblogs.com/zhenyulu/articles/669795.html 博客才明白的,一看是纠结于PreNode队列不知道是什么,原来是自己烦操没看清楚的原因在
这里提醒 如果又犯同样糊涂的猿们小心它是当前点的父节点 的集合。思想的过程讲的很明白再次不一一罗列,感谢博客主人。
先将Java 代码实现的N-路径粘贴如下:
public ArrayList<ArrayList<Integer>> getPaths() {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> onePath = null;// 一条分词路径
Queue queResult = null;
int curNode, curIndex = 0;
int pathIndex = 0;
shortPath();
if (vertex > 0) {
queResult = new Queue();
queResult.push(new QueueNode(vertex - 1, 0, 0));
curNode = vertex - 1;
curIndex = 0;
while (!queResult.isEmpty()) {
while (curNode > 0) {
// Get its parent and store them in nParentNode,nParentIndex
QueueNode qn = parent[curNode].pop(false);
if (qn == null)
qn = parent[curNode].top();
if (qn != null) {
curNode = qn.getParent();
curIndex = qn.getIndex();
}
if (curNode > 0)
queResult.push(new QueueNode(curNode, curIndex, 0));
}
if (curNode == 0) {
// 输出一条分词路径
QueueNode qn = null;
onePath = new ArrayList<Integer>();
onePath.add(curNode);
while ((qn = queResult.pop(false)) != null)
onePath.add(qn.getParent());
result.add(onePath);
queResult.resetIndex();
pathIndex++;// 寻找下一条次短路径
if (pathIndex == pathCount)
break;
// 如果找到有下一个前驱的节点,则把它的这个前驱压入栈中
while ((qn = queResult.pop()) != null) {
curNode = qn.getParent();
QueueNode next = parent[curNode].pop(false);
if (next != null) {
curNode = next.getParent();
next.setWeight(0);
queResult.push(qn);
queResult.push(next);
break;
}
}
}
}
}
return result;
}
shortpath():
/**
* 按列遍历图表,并把每一列中权重最小的取出来。
*
*/
private void shortPath() {
int preNode = -1;
double weight = 0;
if (biSegGraph != null) {
// 图表的列值是从1开始,所以忽略掉第0列
for (int cur = 1; cur < vertex; cur++) {
// 得到同一列的所有元素
ArrayList<SegNode> colSgs = biSegGraph.getNodes(cur, true);
if (colSgs == null || colSgs.size() == 0)
return;
Queue queWork = new Queue();
for (SegNode seg : colSgs) {
preNode = seg.getRow();
weight = seg.getValue();
if (preNode == 0) {
queWork.push(new QueueNode(preNode, 0, weight));
} else {
if (pathWeight[preNode][0] != Utility.INFINITE_VALUE)
queWork.push(new QueueNode(preNode, 0, weight + pathWeight[preNode][0]));
}
}
// 记录每一个节点的N个前驱及权重
QueueNode minNode = null;
int pathIndex = 0;
while ((minNode = queWork.pop()) != null && pathIndex < pathCount) {
pathWeight[cur][pathIndex] = minNode.getWeight();
parent[cur].push(minNode);
logger.debug("pathWeight[" + cur + "][" + pathIndex + "]:" + pathWeight[cur][pathIndex]);
logger.debug("parent[" + cur + "]:" + parent[cur]);
pathIndex++;
}
}
}
}
希望学习ICTCLAS的猿猿们提出自己对这种算法的见解