nodes
& edges
. A node can be directly connected to many other nodes.neighbours
Graphs are a way to model how different things are connected to one another
It helps answer 2 types of questions
Question example
Make a list of friends to search
Q1: is there a path from node A to node B? (is there a mango seller in your network? )
Q2: what is the shortest path from node A to node B? (who is the closest mango seller?)
const graph = { 'you': ['thom', 'jonny']}
Those graphs are equal, but one is directed(only one way), the other is undirected (no arrows)
Python solution
def search(name):
search_queue = deque()
search_queue += graph[name]
searched = []
while search_queue:
person = search_queue.popleft()
if not person in searched:
if person_is_seller(person):
print person + “ is a mango seller!”
return True
else:
search_queue += graph[person]
searched.append(person)
return False
Javascript solution
function search(name){
const searchQueue = graph[name]; // start from the first-level connections
const searched = new Set();
while(searchQueue.length) {
const person = searchQueue.shift();
if(!searched.has(person)) {
if(isPersonSeller(person)) {
console.log(`${person} is a mango seller!`);
return true;
} else {
searchQueue = [...searchQueue, ...graph[person]];
searched.add(person);
}
}
}
return false;
}
function isPersonSeller(name) {
return name.includes('m');
}
find the shortest X
try to modelling your problem as a graph, and use BFS to solve ittrees