Graphs: breadth-first search - Beau teaches JavaScript

freeCodeCamp.org · Beginner ·⚡ Algorithms & Data Structures ·9y ago

Key Takeaways

Implements breadth-first search traversal algorithm in JavaScript

Full Transcript

i gave an introduction about graphs in a previous video in this video i'm going to talk about how to find the distances between two nodes in a graph this is one of the main uses of graphs and is called graph traversal traversal algorithms are algorithms used to traverse or visit nodes in a graph the main types of traversal algorithms are breadth first search and depth first search in this video i will be showing how to implement breadth first search in javascript as you can see the algorithm starts at one node first visits all its neighbors that are one edge away then goes on to visiting each of their neighbors the point is to determine how close nodes are to a root node there are different ways to implement breadth first search in this version you pass in an adjacency matrix graph and the index of the root node remember in an adjacency matrix each nested array in the matrix shows which nodes in the graph are connected to the node at that index for example this array is at index 0 so it shows which nodes that node 0 is connected to if it is connected to a node there is a 1 at that index but if it is not connected there is a 0 at that index before i go through the code let's see it in action so here is a graphical representation of this adjacency graph check out my previous graph video to see how this adjacency graph goes into this graph so we ran the breadth first search function we passed in this graph up here and then we passed in the number one so that means we're trying to find out how far away every node is from the first node so you can see this graphical representation of the exact same graph and if you see the first node right here that's the node we passed in to the the breadth first search function we're going to see how far away each node is so you can see right here it shows how far away is so node zero is two nodes away see because of the direction of the graph we can't just go straight across a zero first from one we go to two then we go to zero so that's two nodes away one the the node itself is always zero nodes away and then the second node is one node away just one third node is three nodes away see first you have to start at one then you go to two then zero then three so that's three hops and four is infinity because when you're on from the first node it's impossible to get to the fourth node because the fourth node only points back to the first node this function will output an object of key value pairs where key is the node and the value is its distance from the root this object will be used to store the distances to the root node we will start all the distances at infinity which in this version of breadth first search indicates that a node is not reachable from the start node here the distance to the root node from the root node is set to zero instead of infinity we are going to create a simple queue to keep track of nodes to visit and the purpose of this variable is to keep track of the current node that we are traversing now we will start a while loop to keep traversing nodes until there are no more nodes in the queue to traverse we'll start the loop by popping off a node from the queue to traverse which at the beginning is the root node here we get all the nodes connected to the current node remember each index of the graph is an array that shows what nodes are connected to the root node associated with that index so in this example we are first looking at node one at node 1 the array shows that it is connected to nodes 0 and 2. now we set the neighbor index variable to an empty array this will keep track of a list of nodes that are connected to the current node this line gets the first node connected to the current node when it says index of 1 this finds the first connected node because the number 1 in our array means that the node is connected to another node at that index if there is no node with an index of one the index variable will be set to negative one so while index does not equal negative one push the index onto our list of neighbors this line searches for the next connected node we look for the next one in the array starting after the previous one we found that's what this plus one means now that we know all the nodes connected to the current node we loop through these connected nodes and get the distance if the value in the node's lin array at the index of the neighbor from the neighbor index array equals infinity that means we haven't set the distance of that node yet so we will set it now we are going to set it to the value of the the node's length array for the current node plus one then we'll push that neighbor to the queue so the next time we go through the while loop we'll check the neighbors of that node too this for loop is the most complicated part of this and you may have to read through it a couple times to completely understand it at the end we return the node's length array and that's breadth first search of a graph thanks for watching my name is beau carnes don't forget to subscribe and remember use your code for good

Original Description

Traversal algorithms are algorithms to traverse or visit nodes in a graph. In this video, I will be showing how to implement breadth-first search traversal algorithm in JavaScript. The algorithm starts at one node, first visits all its neighbors that are one edge away, then goes on to visiting each of their neighbors. The point is to determine how close nodes are to a root node. 💻 Code: https://codepen.io/beaucarnes/pen/XgrXvw?editors=0012 🐦 Beau Carnes on Twitter: https://twitter.com/carnesbeau ⭐JavaScript Tutorials Playlists⭐ ▶JavaScript Basics: https://www.youtube.com/playlist?list=PLWKjhJtqVAbk2qRZtWSzCIN38JC_NdhW5 ▶Data Structures and Algorithms: https://www.youtube.com/playlist?list=PLWKjhJtqVAbkso-IbgiiP48n-O-JQA9PJ ▶Design Patterns: https://www.youtube.com/playlist?list=PLWKjhJtqVAbnZtkAI3BqcYxKnfWn_C704 ▶ES6: https://www.youtube.com/playlist?list=PLWKjhJtqVAbljtmmeS0c-CEl2LdE-eR_F ▶Clean Code: https://www.youtube.com/playlist?list=PLWKjhJtqVAbkK24EaPurzMq0-kw5U9pJh - Learn to code for free and get a developer job: https://www.freecodecamp.com Read hundreds of articles on technology: https://medium.freecodecamp.com And subscribe for new programming videos every day: https://youtube.com/subscription_center?add_user=freecodecamp ❤️ Support for this channel comes from our friends at Scrimba – the coding platform that's reinvented interactive learning: https://scrimba.com/freecodecamp
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from freeCodeCamp.org · freeCodeCamp.org · 16 of 60

1 React: Production Server Setup Part 2 - Live Coding with Jesse
React: Production Server Setup Part 2 - Live Coding with Jesse
freeCodeCamp.org
2 cookies vs localStorage vs sessionStorage - Beau teaches JavaScript
cookies vs localStorage vs sessionStorage - Beau teaches JavaScript
freeCodeCamp.org
3 Browser history tutorial - Beau teaches JavaScript
Browser history tutorial - Beau teaches JavaScript
freeCodeCamp.org
4 Graph Data Structure Intro (inc. adjacency list, adjacency matrix, incidence matrix)
Graph Data Structure Intro (inc. adjacency list, adjacency matrix, incidence matrix)
freeCodeCamp.org
5 React: Parameterized Routing with Next.js - Live Coding with Jesse
React: Parameterized Routing with Next.js - Live Coding with Jesse
freeCodeCamp.org
6 React: Dealing with jQuery Issues - Live Coding with Jesse
React: Dealing with jQuery Issues - Live Coding with Jesse
freeCodeCamp.org
7 setInterval and setTimeout: timing events - Beau teaches JavaScript
setInterval and setTimeout: timing events - Beau teaches JavaScript
freeCodeCamp.org
8 Browser and Device Testing - Live Coding with Jesse
Browser and Device Testing - Live Coding with Jesse
freeCodeCamp.org
9 Last Minute Updates - Live Coding with Jesse
Last Minute Updates - Live Coding with Jesse
freeCodeCamp.org
10 Post Launch Updates - Live Coding with Jesse
Post Launch Updates - Live Coding with Jesse
freeCodeCamp.org
11 React: Setting Up Google Analytics - Live Coding with Jesse
React: Setting Up Google Analytics - Live Coding with Jesse
freeCodeCamp.org
12 React: Masonry Layout - Live Coding with Jesse
React: Masonry Layout - Live Coding with Jesse
freeCodeCamp.org
13 Load Balancing Digital Ocean Droplets - Live Coding with Jesse
Load Balancing Digital Ocean Droplets - Live Coding with Jesse
freeCodeCamp.org
14 try, catch, finally, throw - error handling in JavaScript
try, catch, finally, throw - error handling in JavaScript
freeCodeCamp.org
15 Load Balancing: SSL Passthrough Setup - Live Coding with Jesse
Load Balancing: SSL Passthrough Setup - Live Coding with Jesse
freeCodeCamp.org
Graphs: breadth-first search - Beau teaches JavaScript
Graphs: breadth-first search - Beau teaches JavaScript
freeCodeCamp.org
17 React: Masonry Layout Part 2 - Live Coding with Jesse
React: Masonry Layout Part 2 - Live Coding with Jesse
freeCodeCamp.org
18 React: WordPress API Live Search - Live Coding with Jesse
React: WordPress API Live Search - Live Coding with Jesse
freeCodeCamp.org
19 Creating WordPress Custom Post Types - Live Coding With Jesse
Creating WordPress Custom Post Types - Live Coding With Jesse
freeCodeCamp.org
20 Dates - Beau teaches JavaScript
Dates - Beau teaches JavaScript
freeCodeCamp.org
21 Miscellaneous Front End Updates - Live Coding with Jesse
Miscellaneous Front End Updates - Live Coding with Jesse
freeCodeCamp.org
22 Merging a Pull Request from GitHub - Live Coding with Jesse
Merging a Pull Request from GitHub - Live Coding with Jesse
freeCodeCamp.org
23 React + Prettier + Standard JS - Live Coding with Jesse
React + Prettier + Standard JS - Live Coding with Jesse
freeCodeCamp.org
24 React: Sortable Responsive Table - Live Coding with Jesse
React: Sortable Responsive Table - Live Coding with Jesse
freeCodeCamp.org
25 Geolocation Sorting by Distance - Live Coding with Jesse
Geolocation Sorting by Distance - Live Coding with Jesse
freeCodeCamp.org
26 Tradeoff Matrix - Agile Software Development
Tradeoff Matrix - Agile Software Development
freeCodeCamp.org
27 The Definition of Ready - Agile Software Development
The Definition of Ready - Agile Software Development
freeCodeCamp.org
28 Getting first React job without experience - Ask Preethi
Getting first React job without experience - Ask Preethi
freeCodeCamp.org
29 React: Google Analytics Click Tracking - Live Coding with Jesse
React: Google Analytics Click Tracking - Live Coding with Jesse
freeCodeCamp.org
30 Submitting a PR to an Open Source Project - Live Coding with Jesse
Submitting a PR to an Open Source Project - Live Coding with Jesse
freeCodeCamp.org
31 Should I go back to school to get CS degree? - Ask Preethi
Should I go back to school to get CS degree? - Ask Preethi
freeCodeCamp.org
32 Hero Section CSS Changes - Live Coding with Jesse
Hero Section CSS Changes - Live Coding with Jesse
freeCodeCamp.org
33 Working Agreement - Agile Software Development
Working Agreement - Agile Software Development
freeCodeCamp.org
34 A day at Pennybox with Co-Founder Reji Eapen
A day at Pennybox with Co-Founder Reji Eapen
freeCodeCamp.org
35 React: Sorting and Filtering Data - Live Coding with Jesse
React: Sorting and Filtering Data - Live Coding with Jesse
freeCodeCamp.org
36 React: Sorting and Filtering Data Part 2 - Live Coding with Jesse
React: Sorting and Filtering Data Part 2 - Live Coding with Jesse
freeCodeCamp.org
37 React: Building a New UI - Live Coding with Jesse
React: Building a New UI - Live Coding with Jesse
freeCodeCamp.org
38 Definition of Done - Agile Software Development
Definition of Done - Agile Software Development
freeCodeCamp.org
39 Getting started with jQuery (tutorial) - Beau teaches JavaScript
Getting started with jQuery (tutorial) - Beau teaches JavaScript
freeCodeCamp.org
40 Making a React Blog with WordPress Content - Live Coding with Jesse
Making a React Blog with WordPress Content - Live Coding with Jesse
freeCodeCamp.org
41 React, NextJS, CSS - Live Coding with Jesse
React, NextJS, CSS - Live Coding with Jesse
freeCodeCamp.org
42 jQuery events - Beau teaches JavaScript
jQuery events - Beau teaches JavaScript
freeCodeCamp.org
43 React/NextJS Routing and WordPress API Custom Types - Live Coding with Jesse
React/NextJS Routing and WordPress API Custom Types - Live Coding with Jesse
freeCodeCamp.org
44 React: Working with API Data - Live Coding with Jesse
React: Working with API Data - Live Coding with Jesse
freeCodeCamp.org
45 React: Refactoring Components - Live Streaming with Jesse
React: Refactoring Components - Live Streaming with Jesse
freeCodeCamp.org
46 jQuery effects - Beau teaches JavaScript
jQuery effects - Beau teaches JavaScript
freeCodeCamp.org
47 More React Refactoring - Live Coding with Jesse
More React Refactoring - Live Coding with Jesse
freeCodeCamp.org
48 animate in jQuery - Beau teaches JavaScript
animate in jQuery - Beau teaches JavaScript
freeCodeCamp.org
49 "Finishing" My React Site - Live Coding with Jesse
"Finishing" My React Site - Live Coding with Jesse
freeCodeCamp.org
50 Starting a New React Project (P2D1) - Live Coding with Jesse
Starting a New React Project (P2D1) - Live Coding with Jesse
freeCodeCamp.org
51 React Project 2 Day 2: Learning Material UI - Live Coding with Jesse
React Project 2 Day 2: Learning Material UI - Live Coding with Jesse
freeCodeCamp.org
52 The Agile Manifesto - Agile Software Development
The Agile Manifesto - Agile Software Development
freeCodeCamp.org
53 jQuery: get and set with http, text, val, and attr - Beau teaches JavaScript
jQuery: get and set with http, text, val, and attr - Beau teaches JavaScript
freeCodeCamp.org
54 React Project 2 Day 3 - Live Coding with Jesse
React Project 2 Day 3 - Live Coding with Jesse
freeCodeCamp.org
55 The INVEST approach to product backlog items
The INVEST approach to product backlog items
freeCodeCamp.org
56 React Project 2 Day 4 - Live Coding with Jesse
React Project 2 Day 4 - Live Coding with Jesse
freeCodeCamp.org
57 Chickens and Pigs - Agile Software Development
Chickens and Pigs - Agile Software Development
freeCodeCamp.org
58 React Project 2 Day 5 - Live Coding with Jesse
React Project 2 Day 5 - Live Coding with Jesse
freeCodeCamp.org
59 jQuery: add and remove DOM elements - Beau teaches JavaScript
jQuery: add and remove DOM elements - Beau teaches JavaScript
freeCodeCamp.org
60 React Project 2 Day 6 - Live Coding with Jesse
React Project 2 Day 6 - Live Coding with Jesse
freeCodeCamp.org

Related Reads

Up next
Stump Grinder Carbide Wheel Grinds Hardwood To Chips
Innoforge Studio
Watch →