1. Home
  2. Explore
  3. Computer Science
  4. Graph Theory Introduction

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Graph Theory Introduction

Transcript

Hello and welcome. My name is William and I'm super excited to bring to you this video series focused on graph theory. graph theory is one of my absolute favorite topics in computer science, we're going to see a lot of very awesome algorithms. The whole field is very diverse and hugely applicable to real world applications. I think everybody should be able to learn, love and enjoy graph theory. These first few videos are going to be a ramp up the dose to introduce the topics of how we store represent and traverse graphs on a computer. By the way, this whole video series will be taking on a computer science point of view of graph theory rather than a mathematical one. So we won't be covering proofs, and so on per se. Instead, we'll be looking at algorithm implementation details and code. So what is graph theory? In essence, it is the study of properties and applications of graphs, which common folk or non mathematical folks call networks. This is a very broad topic,

and my goal with this video series is to teach you how to apply graph theory to real world situations. graphs can be used to represent almost any problem which makes them so interesting, because they pop up absolutely everywhere. A simple problem that can be phrased as a graph theory problem might be given the constraints in this picture, how many different sets of clothes Can I make choosing an article from each category? Of course, this could be phrased and solved using only mathematics. But the advantage to graph theory is that it allows us to visualize the problem using nodes to represent an article of clothing and edges to represent relationships between them. Another canonical example of a graph theory problem is a social network of friends. A graph representation enables us to answer interesting questions such as how many friends this person x have, or how many degrees of separation are there

between person x and person y. Now, we have talked about different types of graphs. There are many different types of graph representations. And it's really important, I mean really important to be able to recognize what type of graph you're working with, and especially when you're programming and trying to solve a particular problem. This first type of graph is an undirected graph. It's the most simple kind of graph you'll encounter. And it is where edges have no orientation. That is, if there's an edge from node you to node v, it is identical to the edge from V to U. For instance, in the following graph, nodes are cities and edges represent bi directional roads. Since if you drive from one city to another, you can always retrace your steps by driving the other way. In contrast, to undirected graphs, there are also directed graphs, sometimes called die graphs. In these graphs, you've guessed it, the edges are directed. So if we have an edge from u to v, then you can only go from node

to node v, not the other way around. In this graph, you can see that the edges are directed because of the arrowheads on the edges between nodes. This graph could represent people who bought each other gifts. So an incoming edge represents receiving a gift and an outgoing edge represents giving a gift. Therefore, person e in this graph bought person d a gift, Person A bought themselves and Person B a gift, and person F, about nobody any gifts and received none. So far, we've only seen unweighted graphs, but edges on graphs can contain weights to represent arbitrary values such as cost, distance, quantity, you name it. weighted graphs come in both directed and undirected flavors. As a side note, I will usually denote an edge of a graph as a triplet u, v, w to indicate where an edge is coming from, where it's going to and what its weight is. Of course, with this notation, I also need to specify whether the graph is directed or undirected.

Next up, I just want to have a quick chat about special types of graphs and graph theory. There are so many different types of graphs that I only had to Select a few which will be most relevant for this upcoming video series. The most important type of special graph is definitely the tree. A tree is simply an undirected graph with no cycles. There are several equivalent definitions of a tree such as a graph with n nodes and n minus one edges. All the graphs below are trees. Yes, even the leftmost one since it has no cycles. A related but totally different type of graph is a rooted tree. The distinction here is that a rooted tree has a designated root node, where every edge either points away from or towards the root node. When edges point away from the root node. The graph is called an ABA ressence, or an outreach and an anti arborescens or entry otherwise, out trees are by far more common than entries. From what I've observed. It is also fairly common for people to refer

to a rooted tree simply as a tree instead of an in or out tree. But there is an important distinction there. Next are directed acyclic graphs. These are graphs with directed edges and no cycles. these graphs are very important and fairly common in computer science, actually, since they often are present structures with dependencies, such as a scheduler, a build system, a compiler, maybe, or perhaps more relatable University class prerequisites. There are several efficient algorithms that we'll be looking at to deal specifically with directed acyclic graphs, such as how to find the shortest path and produce a topological ordering of nodes. A topological ordering of nodes is an ordering of nodes that tells you how to process the nodes of the graph so you don't perform a task before first having completed all its dependencies. For example, a topological ordering of class prerequisites would tell you to take intro biology and intro chemistry before taking a class on say genomics.

This next type of special graph is a bipartite graph. It is one whose vertices can be split into two independent groups, u and v such that every edge connects between u and v. This is just a fancy way of saying that the graph is two colorable or that there are no odd length cycles and graph often, a problem we like to ask is what is the maximum matching, we can create on a bipartite graph? Suppose white nodes are jobs and red nodes are people then we can ask how many people can be matched to jobs. In this case, there are a lot of edges in each graph. So I think the answer for both is four. But in general, it's not so easy if there are less edges, tougher constraints and more conflicts. bipartite graphs also play a critical role in the field of network flow, which we will talk about later. This last type of graph is a complete graph is one where there is a unique edge between every pair of nodes in the graph. A complete graph with n vertices is denoted as the graph K

sub n, I have listed k one through k six on the bottom. And you can easily see how this scales when we add more notes. Complete graphs are often seen as the worst case possible graph you can possibly encounter, because of how many edges there are. So if you want to test your algorithm for performance, a complete graph is an easy way to start. One thing we're going to have to be really cognizant about is how we're actually representing our graphs on the computer. This isn't just what type of graph it is, but what type of data structure it but what type of data structure are we representing our graph with. And this can have a huge impact on performance. The simplest way is inside a 2d adjacency matrix. The idea is that the cell MI j represents the edge weight of going from node i to node j. So in the graph below, there are four nodes. So I create a four by four matrix and populate the graph with the

edge weights. If you look at the edge weight from node C to know D, you'll see that Hasn't agitative to. So in a row three and column four of the matrix there is a value of two. Note that is often assumed that the edge of going from a node to itself has a cost of zero, which is why the diagonal of the matrix has all zero values. This matrix form has several advantages. First, that it's very space efficient. For dense graphs. Those graphs with a lot of edges, the ED Jwi lookup can be found in constant time, which is quite nice. And lastly, I would argue that it is the simplest form of graph representation you can have. On the downside however, the main reason people don't go for the adjacency matrix as their first pick, is because it requires v squared space, which is, well a lot of space. In practice graphs with 10,000 nodes or more started to become infeasible very quickly. The other issue with the adjacency matrix is that it requires v squared work

to iterate over all the edges of your graph. This is fine for dense graphs with lots of edges. But it isn't so great for sparse graphs, since most cells will be empty. The main alternative to the adjacency matrix is the adjacency list, which is a way to represent a graph as a map of nodes to list of edges. The idea is that each node tracks all of its outgoing edges. For example, node C has three outgoing edges. So the map entry for C will track the edge from C to A with costs for the Add from C to B, with cost one, and edge from C to D. with cost to notice that, in the list of edges, we only need to track two things, the node we're going to and the cost to get there, we don't need to keep track of where we came from, because that's already implicitly known. The nice thing about adjacency lists is that it is great for sparse graphs, because it only tracks the edges that you have, and doesn't allocate additional memory that you might not use like the adjacency matrix does. This

also means it's efficient when iterating over all the edges. The main disadvantage to using an adjacency list is that it is less space efficient on denser graphs. Another subtle disadvantage is that it takes big O of E time to access a specific edges weight, although in practice, you rarely or if ever actually need to do this. The last representation I want to talk about is the edge list. an edge list is a way to represent a graph simply as an unordered list of edges. Basically, it's exactly what it sounds like a list of edges. Assume that the notation for any triplet u, v w means the cost from node u to node v is W. So for this graph, the edge list is simply a list of six edges represented has those triplets. This representation is very simple. However, it lacks structure. And that's why it is seldomly used. advantage to the Angeles is is great for sparse graphs. iterating over all the edges is super easy, and the structure is simple. The downside is that

edge lookup can be slow, and you can run into memory issues on large graphs. Today, I'm going to talk about common problems in graph theory. A lot of problems you will encounter can often be reduced to a famous or well known problem or some variant thereof. So it's important to be able to familiarize ourselves with common graph theory problems and their solutions. Just before getting started falling off from what we learned in the last video about representing graphs, I want you to think about how you would store and represent the graphs. And the upcoming problems I'm going to describe, in particular, is the graph and the problem I'm describing directed or undirected, are the edges of the graph. weighted or unweighted is the common use case, a graph that is likely to be sparse or dense with edges? And lastly, should I use an adjacency matrix and adjacency list and edge lists or some other structure to represent my graph efficiently? So one of the most if not the most common common

problem in graph theory is the shortest path problem. Given a weighted graph, find the shortest path of edges from node A to node B. So if we pretend this graph represents a road system, and were at node A and want to get to note H, our shortest path algorithm should be able to find us a list of edges to follow that will lead us from A to h with a minimal cost. Lucky for us, many algorithms exist to solve the shortest path problem, including a breadth first search for unweighted graphs. Dykstra is algorithm Bellman Ford, a star and many more. As simple as it sounds, connectivity is a big issue in graph theory. The problem can also be simplified to does there exist a path from node A to node B in this scenario, we don't care about the minimum costs, we just want to know. Can one node reach another node? A typical solution to this problem is to use a union find data structure, or do a very basic search algorithm such as a depth first search or a breadth first search.

Another common problem is detecting negative cycles in a directed graph. Sometimes we're dealing with graphs that have negative edge weights. And we need to know if a native cycle exists, because if there does, it can throw everything off. In this graph nodes One, two and three form a negative cycle. Because if you cycle through all the nodes, you end up with a cost of negative one if you add up all the edge weights, in fact, you can cycle endlessly getting smaller and smaller costs. In the context of finding the shortest path a negative cycle is like a trap that you can never escape. However, there are some contexts where negative cycles are beneficial. Suppose we're trading currencies across an exchange or multiple exchanges. Currency prices try to remain consistent throughout the day across exchanges, such as trading USD to euros or Canadian t yen. But sometimes there are in consistencies in the currency exchange prices. This makes it possible to do something called

an arbitrage, which cycles through multiple currencies exchanging one currency for another and coming back to the original currency with more money than you originally started, at a risk free gain. This is something we can use graph theory for, because it uses detecting negative cycles. There are two well known algorithms that can detect negative cycles. And those are Bellman Ford and Floyd warshall. Some thing that comes up now and again is finding strongly connected components within a graph. This is analogous to finding connected components of an undirected graph. But for directed graphs, when looking at strongly connected components, we're looking for self contained cycles within the graph where every vertex in a given cycle should be able to reach every other vertex in that same cycle. This is very useful in many algorithms as usually an intermediate step. So it's important to know how to find these strongly connected components. And there are many very elegant

algorithms to do so such as Tarzan's algorithm, you probably won't go through your computer science career without hearing about the traveling salesperson problem. The tsp problem is the problem of having n cities and the distances between each of them and finding the shortest path that visits each city and comes back to the original city at minimum cost. For example, if your graph is the one on the left, a possible tsp solution is the graph on the right, which has a cost of nine. The tsp problem is NP hard, meaning it is computationally challenging problem. This is unfortunate because the TSP problem has several very important applications. Some famous algorithms we can use to actually solve this problem or the healed Karp algorithm with dynamic programming doing some kind of branching and bounding algorithm or you can use one of many many approximation algorithms such as the ant colony optimization. This next problem I want to talk about is finding bridges in the graph,

which is something of a fascination to me. bridges are edges which if removed, increase the number of connected components in a graph. And this graph the edges highlighted in pink are bridges. bridges are important in graph theory because they often hint at what points, bottlenecks or vulnerabilities in a graph, think of your graph as a telephone network or a set of bridges between islands, you can immediately see the usefulness of detecting bridges related to bridges, but not the same articulation points, which are nodes that if removed, increase the number of connected components in the graph. In this same graph, you can see the three articulation points highlighted in pink. Next problem is finding the minimum spanning tree of a graph. A minimum spanning tree is a subset of the edges that connects all the vertices together without any cycles and with minimal possible cost. So in summary, it's a tree meaning it

has no cycles, and it spans the graph at a minimal cost. Hence why we give it the name minimum spanning tree. For example, in the graph below, one of the possible minimum spanning trees is this graph with a least cost of 12. Note that all minimum spanning trees of a graph have the same minimal cost, but are not necessarily identical. minimum spanning trees are seen in lots of different applications in computer science, including designing and least cost network circuit design, transportation networks, you name it. There's also several approximation algorithms which rely on minimum spanning trees, which is pretty interesting. If you want to find a minimum spanning tree of a graph, I recommend using one of Kuru schools prims, or beruf cause algorithm. This last problem, I think, is the most fascinating and it is about finding the maximum flow through a special type of graph called a flow network. Flow networks are networks where edge weights

represent capacities and some sense capacities might be things like the maximum amount of cars that fit on a road, or the maximum amount of volume that can flow through a pipe, or even the number of boats a river can sustain without destroying the environment. And these types of flow networks, we often find ourselves asking the question, with an infinite input source, that is cars, water boats, whatever, how much flow? Can I push through the network? Assuming we start at some source and try and make it to some sync node? This question is important, because at some point, there is bound to be a bottleneck somewhere in our flow graph that limits the amount of stuff we can have traveling on the network, making it from point A to point B, the maximum flow would then represent things like the volume of water allowed to flow through the network of pipes, the number of cards, the roads consisting and traffic or the maximum amount of boats allowed on the river. With these maximum flow

problems, we can identify the bottlenecks that slow down the whole network and fix the edges that have lower capacities. We're moving on to talking about the depth first search algorithm, which plays a central role in several graph theory algorithms. So what is the depth first search? A depth first search is a core algorithm in graph theory, that allows you to explore nodes and edges of a graph. So it's a form of traversal algorithm. The nice thing about a depth first search is that it's really easy to code. And it runs in time complexity of big O of a V plus e, that is vertices plus edges, which is directly proportional to the size of your graph. By itself. A depth first search isn't all that useful. But when argumented to perform other tasks, such as count connected components, determine connectivity between nodes, or find bridges and articulation points, the depth first search algorithm really shines. So let's

look at an example. As the name suggests, a depth first search plunges depth first into a graph without regard for which edge it selects next, until it cannot go any further at which point it backtracks and continues its exploration. So a depth first search has to start on a node. And I'm going to start our depth first search on node zero. And now we arbitrarily pick a node to go to some from node zero, we're going to go and do nine. Then from no nine, we only have one choice, which is to go to node eight, at node eight arbitrarily picking edge. So we're going to To go outwards to node seven, node seven, we have plenty of edges to choose from. So let's go to node 10, node 10, to node 11, and 11 to seven. So we don't want to revisit already visited nodes or nodes that are currently being visited. So we have to backtrack to indicate backtracking, I'm going to label edges and nodes as gray, so backtrack all the way back to node seven. So we're not finished exploring node seven,

because there are still edges to be picked. So I'm going to go to node three, and node three, I'm going to go node to node two is a dead end. So we backtrack, then go to node four, node four is also a dead end. So backtrack from node four, back to node three, then pick node threes last edge to go in Node five, five to six, and six to seven, can't go to seven, because we're visiting seven currently, so backtrack all the way back to node eight. from node eight, we still need to visit its last edge, which goes to node one, node one back to node zero, we can't go to node zero, because we're currently exploring it, then backtrack all the way to zero, which completes our depth first search traversal of this graph. So this was one particular depth for search traversal. But as you saw, it could have gone a lot of different ways. So now let's look at some pseudocode. For this depth first search, to get a deeper understanding of how it works. The first thing we need to do is initialize

these three variables, which are n the number of nodes in our graph, g the adjacency. List, representing the graph and visited a Boolean array containing true or false at index i depending on whether or not node i has been visited. In the beginning, this array should have all false values because we have not visited any nodes in the graph. Once that is set up. At the bottom, I define our starting node to be node zero and then called the depth first search method to do the exploration. The depth first search itself has one argument, the current node we are at which I have conveniently named at this method is recursive. So I checked the base case, which is whether we have already visited this node, if so we have no business here and can return otherwise, let's visit this node by marking it as true and exploring all of its neighbors to explore all the neighbors of the node, reach into the adjacency list

and pull out all the neighbors of this node and explore them depth first by looping over each and recursively calling the depth first search method. And that's all a depth first search really is in a nutshell, let's look at another simple use case. For a depth first search. I want you to discuss finding connected components in a graph. First, let's understand what we mean by connected component. Sometimes the graph is split into multiple disjoint components, and it's useful to be able to identify and count these components. One way to identify these components might be to color them so we can tell them apart. But what does coloring nodes really mean to a computer coloring nodes is equivalent to labeling each node is a component with the same ID value. For example, every node in the purple component gets an ID of one, and every node in the green component gets an ID of three, we can use a depth first search to identify components this way. First,

make sure all the nodes are labeled from zero to n non inclusive, where n is the number of nodes, the basic algorithm is to start a depth first search at every node, except if that node has already been visited, and mark all reachable nodes as being part of the same component using the same ID. So if we start at node zero, then we do a depth first search here and then every node in this component gets an ID of zero. So we go to eight, giving it an ID of zero, 14 gets zero 13 or so label it with a zero then backtrack like you do a depth first search, then explore note for given an idea of zero and then finish exploring. That component and then move on to the next node in order. So go to node one next, then node one, so depth for search there. So go node five, label it with a one, five goes to 17, label it with a one, backtrack, go to 16, also label it with a one, we're finished exploring this component, then we would go on to node two, wherever node two

is, then explore that component, then node three, explore node three is component unless node three has already been visited, and so on. So you do this for every component. Eventually, we get to label all the components, and we use a depth first search to do that. Awesome. So that's how we find connected components using a depth first search. Now let's look at some pseudocode. For how we do this, first, we'll need a couple of things. We'll need everything from the previous code we looked at so n, the number of nodes in our graph, G, our adjacency list, and our visited array, but additionally, we'll also need a variable called count that tracks the number of connected components and components an integer array that holds the integer value of which component a node belongs to. Inside the find components method, we loop over every node and check if the current node has been visited or not, and then execute some logic. This depth first search variant differs slightly from the previous

in that we execute a depth first search for every unvisited note, why do we actually do the depth first search, we visit nodes and mark them as visited. So we never revisit the same node more than once we either skip over a node because it's been visited in this for loop or start a depth for search there. If we start a new depth first search, we increment the count variable and keep track of how many depth first searches we have done. Inside the depth first search method itself, the two things we do are mark the current node as visited, and set the current node to be part of the component equal to the value of count, then simply iterate over every neighboring node that has not yet been visited, and call the depth for search method to explore them as well. Back inside the find components method, simply return the number of components and the components array that contains the information about which component each node belongs to. So we've covered two of the things you can

use the depth for search for doing a simple traversal and determining connected components. But we can argument a depth first search to do so much more, such as computer graphs, minimum spanning tree, detect and find cycles in the graph. Check if a graph is bipartite find strongly connected components topologically sought your graph. Find bridges and articulation points find augmenting paths in the flow network generate mazes, and many many more applications. So a depth research is super versatile, and can be extended to do a whole ton of things. Today's topic is the breadth first search graph traversal algorithm. Alongside the depth first search the breadth first search algorithm is another one of those fundamental search algorithms used to explore nodes and edges of a graph. It runs in a time complexity of big O of v plus e that is vertices plus edges, and is often used as a building block in other algorithms. It differs from a depth first search in the way that explores the graph.

The breadth first search algorithm is particularly useful for one thing, finding the shortest path on an unweighted graph. A breadth first search starts at a node in the graph and explores its neighbor nodes first before moving on to explore the next level of neighbors in the sense of breadth first search explores nodes in layers. So if we start breadth first search at zero, we would visit zero first, then visit all zeros neighbors, then we would visit all zeros neighbors, the nodes in yellow before moving on to the next layer of notes, then we would visit all their neighbors and so on. So as you saw a breadth first search expose a graph in a layered fashion, it does this by maintaining a queue of which node it should visit next, this is most easily seen with an example. Let's begin a breadth first search at node zero once more. So let's add zero to the queue on the left. I will denote the current node. in red. This zero is the current

node and we want to add Explore all zeros unvisited neighbors and add them to the queue. So we would add nine to the queue seven to the queue and 11 to the queue. So zero has no more unvisited neighbors. So we move on. So nine is next up in the queue. So we add all of nines unvisited neighbors to the queue. So that is 10, and eight, then there are no more neighbors of nine to visit. So we move on to the next node in our queue, which is seven, then we add all of sevens unvisited neighbors to the queue. So we try and visit node 11. But note 11 is already in the queue, so we don't want to add it again. So we skip it, then we will add six to the queue and three to the queue. Then this process goes on and on until we run out of nodes in the queue. So I will let the animation play. And that's how you do a breadth first search in a nutshell. In the previous animation, we relied on a queue to help us track which node we should visit next. Upon reaching a

new node, the algorithm adds it to the queue to visit it later. The queue dish structure works like a real world queue, such as a waiting line in a restaurant, people can either enter the waiting line that is get in queued or get seeded D queued. Let's look at some pseudocode for the breadth first search. First things first, we'll need to variables and the number of nodes in our graph, and G the adjacency list representing our unweighted graph. This breadth first search function takes two arguments s and E the start and end node indices of the search. The return value for this function is the shortest path of nodes from S to E. I've divided the function into two methods for simplicity. First, we solve the problem by executing the breadth first search and then we reconstruct the path from S to E. So let's take a look at the solve method. So here we are inside the solve method. The first thing I do is initialize the queue data structure that we'll need and add the starting

node to it. This queue should support at minimum the end q n dq operations I just talked about, then initialize a Boolean array with all false values and mark the starting node as visited. This array tracks whether or not node AI has been visited. If the value at index is true, then the node has either been visited or is being visited and is on the queue. And the animation this corresponds to the gray and yellow nodes. The last thing we'll need is an array called prev, which will help us reconstruct the shortest path from the start to the end node. Initially, this array should be initialized with all null values. This array tracks who the parent of node i was, so we can reconstruct the path later. Let's loop while the queue is not empty and plot the top node from the queue by issuing a dq operation, then reach inside the adjacency list and get all the neighbors have this node loop over each unvisited

node. Once we find a next unvisited node and queue it to the queue market as visited and keep track of the parent node of the next node in the prev array. Once the queue is empty, and our breadth first search is complete, simply returns the prev array. Back inside the breadth first search method take the output of the solve method which gave us the prev array and call the reconstruct path method. Here we are inside the reconstruct path method. The first thing we do is actually reconstruct the path by looping backwards from the end node and making our way back to the start node. That is assuming we can reach it. The reason the prep array had to be initialized to all null values is because that is the way and checking whether or not the for loop should stop since we loop through the prev array backwards, starting With the end node, we need to reverse the order of the nodes so that the path starts at the start node and ends at the end node. Last but not least,

we actually have to make sure the path between nodes s and E exists, it might not be possible to reach node II from node s. If the graph is disjoint. If this is the case, then simply return an empty path. Today we're going to talk about using a breadth first search to find the shortest path on a grid. This is going to be a really fun video because we're going to solve a problem. And I'm going to teach you a bunch of handy tricks when doing graph theory on grids. The motivation behind why we're learning about grids in this video is that a surprising number of problems can easily be represented using a grid, which a lot of the times turns into a graph theory problem. grids are interesting because they're a form of implicit graph, which means that we can determine a nodes neighbors based on our location within the grid. For instance, finding a path through a maze is a form of a grid problem you're trying to get from one side of the maze to the other. Well, you need

to find a path that's a pathfinding problem. Or perhaps you're a person trying to navigate your way through obstacles such as trees, rivers, and rocks to get to a particular location. And this can be modeled using a grid, and in turn, we end up using graph theory to navigate around. A common approach to solving graph theory problems on grids is to first convert the grid to a familiar format, such as an adjacency list or an adjacency matrix, so we can easily work with them. However, this isn't always the most efficient technique, but we'll get to that. Suppose we have a grid on the left, and we want to represent it as both an adjacency list and in the adjacency matrix, what do we do first, first, you should label all the cells in the grid with the numbers zero through n non inclusive, where n is the product of the number of rows and columns. So in this grid, on the left, there are six cells. So I labeled each cell with the numbers zero through six not inclusive, then we actually

want to construct an adjacency list and an adjacency matrix. Based off this grid, the adjacency list doesn't require any setup because it's simply a map that we initialize, but the adjacency matrix requires us to initialize a matrix of size six by six to represent our graph, there are six rows and six columns in the new adjacency matrix, because it's how many nodes that are in the grid we're trying to represent. Assuming edges are unweighted, and cells connected left, right up and down. Node zero connects with node one and node two, which we reflect in the adjacency list, and adjacency matrix on the right, then node one connects to node zero and node three, node two to node 03, and four, node three, with nodes one, two, and five, and so on. And that's basically how you convert a grid to an adjacency list or an adjacency matrix. Once we have an adjacency list or an adjacency matrix, we are able to easily

run whatever specialized graph algorithm we need to solve our problems such as finding the shortest path finding connected components, etc. However, transformations between graph representations can usually be avoided due to the structure and the nature of a grid. Let me explain. Suppose where the red ball in the middle and we know we can move left, right up and down to reach adjacent cells. Well, mathematically, if we're the red ball at the row column coordinate r comma C, we can add the row vectors minus 101 comma 00, comma one and zero comma minus one to reach all the adjacent cells. If the problem you're trying to solve allows moving diagonally, then you can also use the row vectors minus one minus one minus 1111 and one minus one. Using row vectors makes it easy to access neighboring cells from the current row column position. First, define the direction vectors for north south east and west broken down into their row column components. Then what

we want to do is loop over each direction vector and add it to the current position here I iterate I from zero to four non inclusive because we only have four directions, then add the Row direction to the current row to make our our the variable representing the new row, and then add the column direction to the current column to make cc the new column position. So the new position on the grid, our comma cc is an adjacent cell. However, it might not be an adjacent cell if we're on the border of the grid, and the new position is out of bounds. So we check that the new coordinate is within our grid by making sure that the new row column position is greater than or equal to zero and doesn't exceed the number of rows and columns of our grid respectively. So if those two checks pass, then we know that the new position r r comma CC, is a neighboring cell of our current position where the red ball was our car seat. So in summary, this

technique is really nice, really easy to code and actually naturally extends to higher dimensions. So let's solve a shortest path problem on a grid using the direct Shin vector technique we just learned about. So here's an abridged problem statement that you might encounter during an interview or in a programming competition. And it goes as follows suppose you're trapped inside a 2d dungeon and need to find the quickest way out. The dungeon is composed of unit cubes, which may or may not be filled with a rock. It takes one minute to move one unit north, south, east, or west, you cannot move diagonally and the maze is surrounded by solid rock on all sides. This problem statement is an easier version of the problem Dungeon Master on the caddis online judge see the problem link in the description. The dungeon is a grid of size R by C and you start at the node with an S character. And there's an exit at the

cell with an IE a cell full of rock is indicated by a pound sign or a hashtag, and empty cells are represented using a.in. This particular setup it's possible to escape the dungeon using this particular route highlighted in green. Remember that we want the shortest path to escape dungeon, not just any path, our approach is going to be to do a breadth first search from the start node until we reach the end node and count the number of cells we traverse during that process. However, it might not be possible to exit the dungeon if we cannot reach the exit, so we'll have to be mindful of that. So like in any breadth first search, we need to start by visiting our start node and adding it to the queue. Assuming we've already found the coordinate of our starting node within the grid we've added to the queue. Then we visit the adjacent unvisited neighbors and add them to the queue as well. And continue this process all the while avoiding adding rock cells to the queue.

So I'll let the animation play And meanwhile, try and predict which cells will be visited next. All right, after we find our end cell, we know how many steps it takes to get from the start to the end. Notice that we didn't even visit all the cells in the grid. The bottom right cell is still unvisited, so it's possible that we terminate early. If you're interested in actually finding the path itself rather than just the number of steps it takes to escape the dungeon, then you'll need to keep track of the previously visited node for each node. Go in and re watch the last video. If you need a refresher on how to do that. I want to talk a little bit about the way we are representing states in our breadth first search. So far, we have been storing the next x y position in the queue as an XY pair. This works well but requires an array or an object wrapper to store the coordinate values. In practice, this can require a lot of packing and unpacking of values to and

from our queue. Let's look at an alternative approach which also scales well in higher dimensions, and in my opinion requires less setup and effort. So the alternative approach I'm suggesting is to use one cue for each dimension. So in a three dimensional grid, you would have one q for each of the x, y and z dimensions. Suppose In queueing the coordinate x one y one Zed one, then we would simply place each coordinate in their respective queues. So the x coordinate goes in the x q, the y goes in its own y, q, and so on. As we need to keep in queueing different positions, we simply keep filling up these queues this way. This contrasts the approach of simply having one queue with each of the components packed away inside an object. The one thing we have to be mindful about, however, is that when we either end keyword dq elements, you need to mq and dq elements from each of the queues all at the same time. So when I dq or pull elements from the queue, I need to

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent