26 lines
		
	
	
		
			589 B
		
	
	
	
		
			JavaScript
		
	
	
	
	
	
			
		
		
	
	
			26 lines
		
	
	
		
			589 B
		
	
	
	
		
			JavaScript
		
	
	
	
	
	
| // https://www.freecodecamp.org/learn/coding-interview-prep/data-structures/depth-first-search
 | |
| 
 | |
| function dfs(graph, root) {
 | |
|   const n_nodes = graph[0].length;
 | |
|   const reachable = new Set([root]);
 | |
|   const stack = [root];
 | |
|   while (stack.length) {
 | |
|     const node = stack.pop();
 | |
|     for (let i = 0; i < n_nodes; i++) {
 | |
|       if (graph[node][i] > 0 && !reachable.has(i)) {
 | |
|         reachable.add(i);
 | |
|         stack.push(i);
 | |
|       }
 | |
|     }
 | |
|   }
 | |
|   return Array.from(reachable);
 | |
| }
 | |
| 
 | |
| var exDFSGraph = [
 | |
|   [0, 1, 0, 0],
 | |
|   [1, 0, 1, 0],
 | |
|   [0, 1, 0, 1],
 | |
|   [0, 0, 1, 0],
 | |
| ];
 | |
| console.log(dfs(exDFSGraph, 3));
 |