Skip to main content
Ctrl+K
Let's LeetCode in Python - Home
  • Introduction

Basics

  • Lectures
    • Lecture 1: Introduction
    • Lecture 2: Data Structure and Dynamic Array
    • Lecture 3: Set and Sorting
    • Hashing
    • Lecture 5: Linear Sorting
    • Lecture 6: Binary Trees - I
    • Lecture 7: Binary Trees - II
    • Lecture 8: Binary Heap
    • Lecture 9: Breadth-First Search
    • Lecture 10: Depth-First Search
    • Lecture 11: Weighted Shortest Path
    • Lecture 12: The Bellman-Ford Algorithm
    • Lecture 13: The Dijkstra’s Algorithm
  • Overview

Convex-optimization

  • Interior-point Method
  • Newton Iterative Method

Leetcode

  • Solutions
    • 0001. Two Sum
    • 0003. Longest Substring without Repeating Characters
    • 0004. Median of Two Sorted Arrays
    • 0005. Longest Palindromic String
    • 0015. Three Sum
    • 0016. Three Sum Closest
    • 0018. Four Sum
    • 0021 Merge Two Sorted Lists
    • 0022 Generate Parentheses
    • 0023 Merge k Sorted Lists
    • 0026 Remove Duplicates
    • 0027 Remove Element
    • 0048 Rotate Image
    • 0054 Spiral Matrix
    • 0056 Merge Intervals
    • 0059 Spiral Matrix II
    • 0076 Minimum Window Substring
    • 0083 Remove Duplicates From Sorted List
    • 0086 Partition List
    • 0092. Reversed Linked List ii
    • 0115 Distinct Subsequences
    • 0123 Best Time to Buy and Sell Stock III
    • 0160 Intersection of Two Linked List
    • 0167. Two Sum II
    • 0189. Rotate Array
    • 0200. Number of islands
    • 0206. Reversed Linked List
    • 0207 Course Schedule
    • 0226. Invert Binary Tree
    • 0236 Lowest Common Ancestor of a Binary Tree
    • 0279 Number Squares
    • 0300 Longest Increaseing Subsequence
    • 0303 Range Sum Query
    • 0304 Range Sum Query - 2D
    • 0323 Number of Connected Component in an Undirected Graph
    • 0344. Reverse String
    • 0354 Russian Doll Envelope
    • 0370 Range Addition
    • 0438 Find All Anagrams in a String
    • 0463. Island Perimeter
    • 0494 Target Sum
    • 0547 Number of Provinces
    • 0567 Minimum Window Substring
    • 0652 Find Duplicate Subtrees
    • 0695. Max Area of Island
    • 0704. Binary Search
    • 0712 Minimum ASCII Delete Sum for Two Strings
    • 0713 Subarray with a product less than k
    • 0733. Flood Fill
    • 0733. Network Delay Time
    • 0797 All Paths From Source to Target
    • 0886 Possible Bipartition
    • 1027 Longest Arithmetic Subsequence
    • 1109 Flight Booking
    • 1288 Remove Covered Intervals
    • 1514 Path With Maximum Probability
    • 1584 Min Cost to Connect All Points
    • 1631 Path With Minimum Effort
    • 1976 Number of Ways to Arrive at Destination

Notes

  • Algorithm
    • Backtracking
    • Big-O Complexity
    • Graph algorithm
    • Recursion
    • Search
    • Sort
  • Data Structure
    • Chapter 1. Array and String
    • Dynamic Programming II
    • Chapter 11. Dynamic Programming III
    • Dynamic Programming IV
    • Chapter 12. Backtracking
    • Chapter 2. Singely Linked List
    • Chapter 3. Stack
    • Chapter 4. Binary Search Tree
    • Cahpter 5. Binary Tree
    • Chapter 6. Binary Search Tree II
    • Chapter 7: Binary Heap
    • Chapter 8. Graph
    • Chapter 9. Dynamic Programming I
  • Repository
  • Open issue
  • .ipynb

Lecture 9: Breadth-First Search

Contents

  • Rrepresentations of Graph
    • Adjancency-list Representation
    • Adjancency-matrix Representation
    • Implementation of Vertex/Edge Attributes
  • Breadth-First Search
  • Shortest Path

Lecture 9: Breadth-First Search#

Rrepresentations of Graph#

There are two ways to represent a graph \(G = (V, E)\): as a collection of adjacency lists or an adjacency matrix. Either way applies to both directed and undirected graphs.

  • Adjacnecy-list representation provides a compact way to represent Sparse graphs: \(|E|\) is way less than \(|V^2|\).

  • Adjacency-matrix representation when the graph is dense

    • can help quickly to tell if there is an edge connecting two vertices.

graph-representation.

Adjancency-list Representation#

  • The graph \(G=(V,E)\) consist of an array G.Adj of \(|V|\) lists, one for each \(V\).

  • For each \(u \in V\), the adjacency list \(Adj[u]\) containts all the vertices \(v\) such that there is an edge \((u,v) \in E\), or contains pointers to these vertices.

  • The sum of length of all the adjacency lists

    • \(2*|E|\) for undirected graph

    • \(|E|\) for directed graph

  • Similarly, we can define an associated attirbute \(w\) as \(G.w\) to represent weighted graphs. -. \(G.w[u]\).

  • Disadvantages:

    • \(O(|E|)\) time to determine if an edge \((u, v)\) is present in the graph

Adjancency-matrix Representation#

  • The adjacency matrix \(A\) is \(|V|\)-by-\(|V|\) so that \(a_{i,j} = 1\) if \((i, j)\in E\) else 0

  • Requires \(O(V^2)\) space

  • Preferred when graphs are reasonably small.

Implementation of Vertex/Edge Attributes#

  • Attributes such as adjacency list, weights can be annotated as G.Adj, G.w.

  • Similar for vertice or edge attributes: u.d, (u,v).f etc.

  • But how to implement these attributes in programs??

    • depends on language and algorthm needs

Breadth-First Search#

  • Given a graph \(G\) and a distinguished source \(s\), BFS explores the edge of \(G\) to discover every vertex that is reachable from s and return a breadth-first tree with root s that contains the shortest path from s to v for each v reachable from s.

  • breadth-first: discover all vertices at distance k from s before discovering any vertices at distance k+1.

bfs

  • psedocode: assuming adjacency-list representation

def BFS(G,s):
    for u in G.V:                       # Initialize all vertices --> O(V)
        u.color = WHITE                 # Mark all vertices as unexplored --> O(1)
        u.d = inifinity                 # Initialize the distance to infinity --> O(1)
        u.p = NIL                       # Initialize the parent to NIL --> O(1)
    s.color = GRAY                      # Start to explore vertice s --> O(1)
    s.d = 0                             # Set the root distance as 0 --> O(1)

    Q = []                              # Initialze a queue to store Gray vertices --> O(1)
    enqueue(Q, s)                       # Put root s in the queue --> O(1)
    while Q != []:                      
        u = dequeue(Q)                  # Dequeue Q to explore the first vertice u in the queue --> O(1)
        for v in G.Adj[u]:              # Explore adjacenct list of u --> O(E)
            if v.color == WHITE:        # If v is unexplored yet, add to the queue for exploring
                v.d = u.d + 1           # Update distance of v
                v.color == GRAY         # Mark vertice as exploring
                v.p = u                 # Set parent vertice
                queue(Q, v)             # Add vertice to queue for future exploring
        u.color = BLACK                 # Finish exploration of u and mark

Shortest Path#

  • After running BFS on a graph, we can get all the shortest paths from s to any reachable vertice v as a breadth-first tree

  • How to obtain the shortest path from s to v??

    • run BFS on G

    • recursively check the parent of v until reach s

def shortest_path(G,s,v):
    if v==s:
        return s
    elif v.p == NIL
        print("No path from s to v exists")
    else:
        shortest_path(G, s, v.p)

previous

Lecture 8: Binary Heap

next

Lecture 10: Depth-First Search

Contents
  • Rrepresentations of Graph
    • Adjancency-list Representation
    • Adjancency-matrix Representation
    • Implementation of Vertex/Edge Attributes
  • Breadth-First Search
  • Shortest Path

By Yangyang Fu

© Copyright 2023.