我把元素最后一位为'h'的设为我们要查询的元素。
//广度优先搜索。

//使用对象创建一个图
var photo = {};
photo.you = ['Bob','bog','cat'];
photo.Bob = ['Alice','milk'];
photo.bog = ['milk','mouse'];
photo.cat = ['fish','rabbit'];
photo.Alice = [];
photo.milk = ['bog'];
photo.mouse = [];
photo.rabbit = [];
photo.fish = ['cat'];
//创建搜索函数
function find(){
var queue = [];//使用数组创建一个队列(假的只实现尾部添加,首部删除)
queue = queue.concat(photo.you);//在队列中加入根部you;
var last = [];//创建一个存储一查找过得元素的存储数组,避免无方向图导致的无限循环
while(queue.length > 0){
var first = queue.shift();//从队列中获取第一个元素并赋值给first
if(last.indexOf(first) < 1){ //判断所查找的元素是否已经查找过
if(first){ //判断查找的元素是否为空,若为空split('')可能会出错
if(first.split("").pop() == 'h'){ //我们使尾部为h的元素设为是我们需要查找的
return true
}else{
queue = queue.concat(photo[first]);//把依赖本次查找的元素加入查询队列中
last.push(first) //已经查找过,加入查找过的存储数组
}
}
}
}
return false//如果没有则返回false
}
网友评论