threejs 组成的3d管道,寻最短路径问题

threejs 里面的3d管道的每个节点ID是唯一的,且对应x,y,z坐标。那么当需要从A点到B点的时候,可能出现有多条路径可走,此时便需要求出最短行走路径,因此用到一个寻路径算法。我们将问题简化如下:

后记:事实证明,下面这个算法有点缺陷,哈哈,其实少了一个查找深度,否则路径多的情况下会死掉,chrome dev会报 over max stack ~~ so, 加上一个递归深度就搞定了撒~~

var begId = 191; //起点ID
var endId = 185; //终点ID

//所有路径,不区分开始和结束节点的前后顺序
var allPaths = [[185,184],[186,185],[187,186],[188,187],[189,187],[191,189]];
var result = [];

var tree_num = 1;
var over_num = 0;

/*
pos 	=> 起点坐标id
target 	=> 终点坐标id
key	=> 返回的字符串,保存上一层递归完成的路径节点
len 	=> 节点的id差(本例中没用到)
pos0	=> 原始起点,防止走回头路
*/


function tree(pos, target, key, len, pos0)
{

var _index = 0;

var others = [];

var tmp = '';

for(x in allPaths)
{
	// one point is pos
	if (allPaths[x] [0] == pos || allPaths[x] [1] == pos)
	{
		var other = allPaths[x] [0] == pos ? allPaths[x] [1] : allPaths[x] [0];

		if ( (pos > target && (other >= pos || other >= pos0 ) ) || (pos < target && (other <= pos || other <= pos0 ) ) ) continue;

		others.push(other);

		if (_index > 0)
		tree_num ++;

		_index ++;
	}
}


for(y in others)
{
	other = others[y] ;
	len += other - pos;

	// other one is end?
	if (other == target)
	{
		result.push(key+target+",|"+len);
		over_num ++;
		continue;
	}
	// else if (other > endId) continue ?
	tree(other, target, key+other+",", len, pos0);
}

// all tree over ?
if (tree_num == over_num)
{
	// console.log(result);
}
}

function get_short_path(a,b){
	tree(a,b,"",0, a);
	var ret = result;
	result = [];
	var min = 100;
	var min_path_str = '';
	//求出最短的路径
	for (x in ret)
	{
		var path_arr_str = ret[x].split('|')[0];
		var path_arr = path_arr_str.split(",");
		var rank = path_arr.length;
		if (rank < min) 
		{
			min = rank;
			min_path_str = path_arr_str;
		}
	}
	return min_path_str.slice(0,-1).split(",");
}

// tree(begId, "", 0);

var search_arr = [[185,188],[191,184]];

for ( var x in search_arr)
{
	var ret = get_short_path(search_arr[x][0], search_arr[x][1]);
	console.log(ret);
}
posted @ 2015-03-04 14:13  前端小小菜  阅读(1469)  评论(0编辑  收藏  举报