Data Structures: Breadth-First Search
This commit is contained in:
		
							parent
							
								
									f4b4db0d8b
								
							
						
					
					
						commit
						be75ed68ed
					
				
							
								
								
									
										34
									
								
								Data Structures/bfs.js
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										34
									
								
								Data Structures/bfs.js
									
									
									
									
									
										Normal file
									
								
							@ -0,0 +1,34 @@
 | 
				
			|||||||
 | 
					// https://www.freecodecamp.org/learn/coding-interview-prep/data-structures/breadth-first-search
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					function bfs(graph, root) {
 | 
				
			||||||
 | 
					  const nodesLen = {};
 | 
				
			||||||
 | 
					  const n_nodes = graph[root].length;
 | 
				
			||||||
 | 
					  for (let dst = 0; dst < n_nodes; dst++) {
 | 
				
			||||||
 | 
					    nodesLen[dst] = Infinity;
 | 
				
			||||||
 | 
					  }
 | 
				
			||||||
 | 
					  nodesLen[root] = 0;
 | 
				
			||||||
 | 
					  for (let q = [root], d = 1; ; d++) {
 | 
				
			||||||
 | 
					    const newQ = [];
 | 
				
			||||||
 | 
					    for (let src of q) {
 | 
				
			||||||
 | 
					      for (let dst = 0; dst < n_nodes; dst++) {
 | 
				
			||||||
 | 
					        if (nodesLen[dst] > d && graph[src][dst] > 0) {
 | 
				
			||||||
 | 
					          nodesLen[dst] = d;
 | 
				
			||||||
 | 
					          newQ.push(dst);
 | 
				
			||||||
 | 
					        }
 | 
				
			||||||
 | 
					      }
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					    if (newQ.length <= 0) {
 | 
				
			||||||
 | 
					      break;
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					    q = newQ;
 | 
				
			||||||
 | 
					  }
 | 
				
			||||||
 | 
					  return nodesLen;
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					var exBFSGraph = [
 | 
				
			||||||
 | 
					  [0, 1, 0, 0],
 | 
				
			||||||
 | 
					  [1, 0, 1, 0],
 | 
				
			||||||
 | 
					  [0, 1, 0, 1],
 | 
				
			||||||
 | 
					  [0, 0, 1, 0],
 | 
				
			||||||
 | 
					];
 | 
				
			||||||
 | 
					console.log(bfs(exBFSGraph, 3));
 | 
				
			||||||
		Loading…
	
		Reference in New Issue
	
	Block a user