Go语言 算法图解——广度优先搜索

具体知识内容参考《算法图解》P77

package main

import "fmt"

func personIsSeller(name string) bool {
	//判断是否是芒果销售商,名称已M结尾
	return name[len(name)-1] == 'M'

}
func breadthFirstSearch(friendCircle map[string][]string) bool {
	seachList :=friendCircle["you"]
	if len(seachList) == 0 {
		return false
	}
	//已经找过的人
	seached := make(map[string]bool)
	for {
		person := seachList[0]
		seachList = seachList[1:]
		//map[key]:返回的第一个值为key对应的value,第二个值为是否键值对是否存在
		_, found := seached[person]
		//此人没有遍历过
		if !found {
			if personIsSeller(person) {
				fmt.Println(person,"是芒果销售人员")
				return true
			}else{
				seachList=append(seachList,friendCircle[person]...)//此人的朋友加入到搜索队列中(两个切片相连接)
				seached[person]=true
			}
		}
		if len(seachList)==0 {
			break
		}
	}
	return false

}
func main() {
	map1 := make(map[string][]string)
	//一度关系
	map1["you"] = []string{"BOB", "ALICE", "CLAIRE"}
	//二度关系
	map1["BOB"] = []string{"ANUJ", "REGGY"}
	map1["ALICE"] = []string{"PEGGY"}
	map1["CLAIRE"] = []string{"THOM", "JONNY"}
	//三度关系
	map1["ANUJ"] = []string{}
	map1["REGGY"] = []string{}
	map1["THOM"] = []string{}
	map1["JONNY"] = []string{}

	m:=breadthFirstSearch(map1)
	fmt.Println(m)

}

 

你可能感兴趣的:(Go语言 算法图解——广度优先搜索)