1 of 31

CSE 373 SP25 AX Section 8

Graph Algorithms and Design

2 of 31

Check-In

What is the last video game you played?

3 of 31

Announcements

  • Two-Stage Exam 3 Tomorrow in CSE2 G20 at 12:30 PM!
    • Any content up until 5/22 is fair game for this quiz.
    • Check your email for assigned seating by today!
    • 10 A4 pages of notes are allowed, bring a pencil/pen and Student ID too.
    • Exam Format/Prep? Practice Exam! Lecture Qs! Section Qs! Prework!
  • Project: Shortest Paths Project Code due next Tuesday (May 27th)!

4 of 31

Dijkstra’s Algorithm: single-pair-shortest-path

  • Pathfinding on a weighted graph!�
  • Main idea: find shortest path/shortest distance from start node in graph to every other node.�
  • Uses a Priority Queue, where priorities of nodes are their distance from the start node�
  • We pull the closest node off the queue each iteration, and update the distances for its adjacent nodes. Then repeat.

5 of 31

Dijkstra’s Review

6 of 31

Buggy Dijkstra’s

  • Find the bug(s) in this pseudocode, explain why the behavior isn’t correct, and suggest a fix.

dijkstraShortestPath(G graph, V start, V end)

Set known; Map edgeTo, distTo;

initialize distTo with all nodes mapped to infinity, except start to 0

while (there are unknown vertices):

let u be the closest unknown vertex

known.add(u)

for each edge (u,v) to unknown v with weight w:

if (v == end)

return path // We found the goal node, we’re done!

oldDist = distTo.get(v)

newDist = distTo.get(u) + w

if (newDist < oldDist):

distTo.put(v, w)

edgeTo.put(v, u)

7 of 31

Buggy Dijkstra’s - Solution (Link)

  • One key issue is we return the path as soon as we find goal, without making sure that edge is the shortest one - the return is when the goal node is officially visited or processed.
    • if (v == end): return path // We found the goal node, we’re done!
  • When checking if the newDist is less than the oldDist, the value put in shouldn’t be w for the single edge but a sum of the path including that edge. (include distTo.get(u) or newDist)
    • if (newDist < oldDist): distTo.put(v, w)

8 of 31

Run Dijkstra’s algorithm on the graph below starting at the vertex 0. The table to the right shows the results right after 2’s edges have been relaxed.

  1. In what order were the vertices visited before the vertex 2 was visited? �Walk through the steps of the Dijkstra’s algorithm starting from 0 and ending at 2.
  2. 0 , __ , __ , __ , 2
  3. What vertex will be visited next after 2 is visited, and why?

  1. Update the table after the vertex you identified from (b) is visited (i.e. after all its edges are relaxed).

vertex

distTo

edgeTo

0

0

-

1

-

2

5

4

3

1

0

4

4

0

5

8

2

6

6

4

7

2

3

2

0

1

3

4

5

6

7

8

2

4

1

5

1

3

9

1

3

3

1

20

9 of 31

Shortest Paths (solution)

Suppose that we run Dijkstra’s algorithm on the graph below from the vertex 0.

The table to the right shows the results right after vertex 2’s edges have been relaxed.

  1. In what order were the vertices after 0 and before 2 visited?
  2. 0 , 3 , 7 , 4 , 2

  1. What vertex will be visited after 2? 6
  2. Has the lowest distTo value out of remaining unvisited vertices

vertex

distTo

edgeTo

0

0

-

1

-

2

5

4

3

1

0

4

4

0

5

8

2

6

6

4

7

2

3

10 of 31

Shortest Paths (solution)

c. Update the table after the vertex you identified from (b) is visited (i.e. after all its edges are relaxed).

vertex

distTo

edgeTo

0

0

-

1

26

6

2

5

4

3

1

0

4

4

0

5

7

6

6

6

4

7

2

3

11 of 31

Graph Design Scenarios

12 of 31

Graph Design: Scenario 1

  • Consider the following scenario:

Anna is commuting from her home to campus to teach lecture. However, before stepping foot in the lecture hall, she needs to print out the lecture worksheets. With this in mind, Anna is trying to calculate the shortest path she can take from her house to the lecture hall that includes a stop at a printer. How might she achieve this?

  • Assumptions:
    • Assume multiple places on campus have a printer
    • Assume edge weights are by distance and nodes are buildings on campus and her home

13 of 31

Graph Design: Scenario 1 Solution

  • What we know
    • Shortest path
    • Weighted edges
  • Must be Dijkstra's!
  • A single run of Dijkstra’s doesn’t work
    • Dijkstra’s assumes you are trying to find the shortest path from a single source to a single destination
  • How can we fix this? We can run Dijkstra’s multiple times
    • 2 approaches:
      • Run Dijkstra’s from Anna’s house to get the shortest path to every printer. Then, run Dijkstra’s from every printer to the lecture hall.
      • Run Dijkstra’s from Anna’s house to get the shortest path to every printer. Then, run Dijkstra’s again from the lecture hall to find the shortest path from there to every printer.
  • Difference is one implementation runs Dijkstra’s many times the other runs it twice!

14 of 31

Graph Design: Scenario 1 Solution

Run Dijkstra’s from Anna’s house to get the shortest path to every printer. Then, run Dijkstra’s again from the lecture hall to find the shortest path from there to every printer.

Aelysha’s Drawing:

15 of 31

Graph Design: Scenario 1 Solution

Run Dijkstra’s from Anna’s house to get the shortest path to every printer. Then, run Dijkstra’s again from the lecture hall to find the shortest path from there to every printer.

Aelysha’s Drawing:

16 of 31

Graph Design: Scenario 2

  • Consider the following scenario

Anna is walking her dog Percy and knows Percy's favorite spots to use the bathroom. She wants to try to make it home whilst simultaneously minimizing the amount of times that she has to stop and let Percy use the bathroom. Return any 5 distinct paths Anna can take to get to her house that minimize the amount of times she has to stop and let Percy use the bathroom.

  • Assumptions:
    • Her dog can use the bathroom multiple times
    • No edge weights, and we don’t care about distance
    • Bathroom spots will be marked on the graph as special nodes

17 of 31

Graph Design: Scenario 2 Solution

  • What we know
    • No edge weight
    • Not necessarily worried about shortest path
  • Let’s use DFS!
  • Solution:
    • Explore all possible paths to Anna’s home from her destination using DFS. Add to a path list when you visit a node.
    • Record the path once you reach the destination node.
    • Update a counter for every time you pass by one of the bathroom areas.
    • Add paths and counts to a list once you have 5 recorded and sort them based on the fewest number of bathroom stops. Return this list.

18 of 31

Graph Design: Scenario 2 Solution

  • DFS

Aelysha’s Drawing:

19 of 31

Graph Design: Scenario 3

Suppose we are trying to design a maze within a 2d top-down video-game. The world is represented as a grid, where each tile is either an impassable wall, an open space a player can pass through, or a wormhole. On each turn, the player may move one space on the grid to any adjacent open tile. If the player is standing on a wormhole, they can instead use their turn to teleport themselves to the other end of the wormhole, which is located somewhere else on the map.

Now, suppose that there are several coins scattered throughout the map. Your goal is to design an algorithm that finds a path between the player and some coin in the fewest number of turns possible.

  1. Describe how you would represent this scenario as a graph.
  2. Describe how you would implement an algorithm to complete this task.

20 of 31

Scenario 3 - Solution (Link)

  1. Tiles = nodes in our graph, edges are unweighted + undirected.
    1. Each tile is connected with one edge, while the wormhole needs an extra edge to connect to its endpoint.
  2. One turn = one edge weight, so no need for weights (no difference in cost). Also, a player can travel in any direction.
    • If any paths are one-way, can convert graph to directed.
    • Shortest path to coin: Use BFS, where goal = reach coin (T/F)

21 of 31

Leetcode - Graphs!

22 of 31

Why LeetCode Style Code Challenges?

  • Improvement on Algorithmics:
    • Be aware that such problems exist
    • Practice thinking through problems
    • Coming up with various approaches and solutions
    • Get comfortable with various data structures and algorithms
    • Better sense of what tools, approaches, strategies, refinements you can make
  • Improvement on Communication & Comprehension:
    • Be able to communicate approaches, solutions, thought processes outloud
    • Be able to refine thoughts and convey them effectively
    • Real-life interview-style practice
    • More about the process than the results
  • Get to interact with other classmates and HAVE FUN!

23 of 31

Instructions

Each group of 3 or 4 students will be assigned the following problem:

  • LeetCode 994: Rotting Oranges
  • LeetCode 743: Network Delay Time

Different Approaches to Use:

  • Brute Force
  • BFS
  • DFS
  • Dijkstra's Algorithm�

For instructions, search online for the problem by ID number, e.g. “LeetCode 347”.

We will have about 20 minutes for this activity:

  • Groups will get together and work on coming up with a general solution approach to the problem for 15 minutes
  • TAs will go over a sample solution for the last 5 minutes of the activity

NO NEED to write up code for this activity. Try to come up with solution approaches and how you would tackle the program on the high-level using specific data structures.

24 of 31

Different Approaches Available

  • Brute Force
  • Breadth-First Search
  • Depth-First Search
  • Dijkstra's Algorithm

25 of 31

Presentation Guidelines

Questions to Ask Yourself:

  • What is the problem really asking?
  • What operations do I need to perform often?
  • In the examples, are there patterns that can help getting started?
  • When should I use specific data structures?

Presentation Guidelines

  • Explain how you approached the problem
  • Run through how you eliminated other options
  • Describe the data structure(s) and algorithm(s) you chose and why
  • Go through your solution step by step, explaining the logic

Complete the reflection activity in Gradescope and add your groupmates!

26 of 31

Example Solution - LeetCode 994 (Super-Source BFS Trick)

class Solution {

public int orangesRotting(int[][] grid) {

int m = grid.length;

int n = grid[0].length;

int[][] visited = grid;

Queue<int[]> q = new LinkedList<>();

int countFreshOrange = 0;

for (int i = 0; i < m; i++) {

for (int j = 0; j < n; j++) {

if (visited[i][j] == 2) {

q.offer(new int[] {i, j});

}

if (visited[i][j] == 1) {

countFreshOrange++;

}

}

}

if (countFreshOrange == 0)

return 0;

if (q.isEmpty())

return -1;

int minutes = -1;

int[][] dirs = {{1, 0},{-1, 0},{0, -1},{0, 1}};

while (!q.isEmpty()) {

int size = q.size();

while (size-- > 0) {

int[] cell = q.poll();

int x = cell[0];

int y = cell[1];

for (int[] dir : dirs) {

int i = x + dir[0];

int j = y + dir[1];

if (i >= 0 && i < m && j >= 0 && j < n && visited[i][j] == 1) {

visited[i][j] = 2;

countFreshOrange--;

q.offer(new int[] {i, j});

}

}

}

minutes++;

}

if (countFreshOrange == 0)

return minutes;

return -1;

}

}

27 of 31

Example Solution - LeetCode 743 (Min-Heap Dijkstra’s Algorithm)

public int networkDelayTime_Dijkstra(int[][] times, int N, int K) {

Map<Integer, List<int[]>> graph = new HashMap<>();

for (int[] edge: times) {

graph.putIfAbsent(edge[0], new ArrayList<>());

graph.get(edge[0]).add(new int[]{edge[1], edge[2]});

}

PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> (a[0] - b[0]));

boolean[] visited = new boolean[N + 1];

int[] minDis = new int[N + 1];

Arrays.fill(minDis, Integer.MAX_VALUE);

minDis[K] = 0;

pq.offer(new int[]{0, K});

int max = 0;

while (!pq.isEmpty()) {

int[] curr = pq.poll();

int currNode = curr[1];

if (visited[currNode]) continue;

visited[currNode] = true;

int currDis = curr[0];

max = currDis;

N--;

if (!graph.containsKey(currNode)) continue;

for (int[] next : graph.get(currNode)) {

if (!visited[next[0]] && currDis + next[1] < minDis[next[0]])

pq.offer(new int[]{currDis + next[1], next[0]});

}

}

return N == 0 ? max : -1;

}

28 of 31

Reference Slide - DFS

dfs(Graph graph, Vertex start) {

Stack<Vertex> perimeter = new Stack<>();

Set<Vertex> visited = new Set<>();

perimeter.add(start);

while (!perimeter.isEmpty()) {

Vertex from = perimeter.remove();

if (!visted.contains(from)) {

for (Edge edge:graph.edgesFrom(from)) {

Vertex to = edge.to();

perimeter.add(to)

}

visited.add(from);

}

}

}

29 of 31

Reference Slide - BFS

...

Map<Vertex, Edge> edgeTo = ...

Map<Vertex, Double> distTo = ...

edgeTo.put(start, null);

distTo.put(start, 0.0);

while (!perimeter.isEmpty()) {

Vertex from = perimeter.remove();

for (Edge edge : graph.edgesFrom(from)) {

Vertex to = edge.to();

if (!visited.contains(to)) {

edgeTo.put(to, edge);

distTo.put(to, distTo.get(from) + 1);

perimeter.add(to);

visited.add(to);

}

}

}

return edgeTo;

}

30 of 31

Reference Slide - Dijkstra’s (Pseudocode)

dijkstraShortestPath(G graph, V start)

Set known; Map edgeTo, distTo;

initialize distTo with all nodes mapped to ∞, except start to 0

while (there are unknown vertices):

let u be the closest unknown vertex

known.add(u)

for each edge (u,v) to unknown v with weight w:

oldDist = distTo.get(v) // previous best path to v

newDist = distTo.get(u) + w // what if we went through u?

if (newDist < oldDist):

distTo.put(v, newDist)

edgeTo.put(v, u)

31 of 31

Closing Announcements

  • Thanks for coming to section! See you tomorrow in class for Exam 3! Stay safe and stay hydrated :)
  • Extra Resub details - to come soon!

Please don't hesitate to reach out if you have any

questions or concerns about the course, or if there's

anything else we can help you with! We're here to support

you however we can!