This article is my own study of “algorithm diagram” some reading notes, ability is general, the level is limited, there is a bad place, welcome to point out
Question: How do I find the mango merchant through the least connected person in my circle of friends?
If you don’t have any friends of your own, then you should go to the friends of your friends
Queues do a better job of doing this by adding your friends to the queue first
If not, the mango merchant leaves the queue and adds his friends to the queue until it is found or all searched
The complete code is as follows:
Class Search {constructor() {this.map = {} this.searchable = {} // To record the searched values /* To use objects to store friendships similar to this map = {start: searchable; ["alice", "bob", "claire"], bob: ["anuj", "peggy"], alice: ["peggym"], claire: ["tho", "jonny"], anuj: ['yasd'], Peggym: ['test'], Thom: [' Boolj '], Jonny: ['we'],} */} addNode(start, end) { This.map [start]) {this.map[start] = []} this.map[start].push(end)} BFS () {// Queue = this.map.start; While (queue.length) {let node = queue[0]; If (isSearchOf(node)) {return node} if (! IsSearchOf (node)) {if (this.map[node] && this.map[node].length) {// Prevent repeated search a-b-c-a if (! Searchable [node]) {queue = queue.concat(this.map[node])}} Let val = queue.shift() this.search [val] = true}} return false function searchof (name) {return!! (name[name.length - 1] === 'm') } } } let graph = new Search() graph.addNode('start', 'alice') graph.addNode('start', 'bob') graph.addNode('start', 'claire') graph.addNode('bob', 'anuj') graph.addNode('bob', 'peggy') graph.addNode('alice', 'peggy') graph.addNode('claire', 'thom') graph.addNode('claire', 'jonny') console.log(graph.bfs())Copy the code