Data Structure Algorithm

Array & LinkedList

Professional Practice

  • Chunk it up
  • Delibrate practice
  • Feedback

How to solve problem

  1. clarification
  2. possible solutions
    1. time/space
    2. optimal
  3. Coding multiple times
  4. Test (edge) cases

Data Structure

  • Vector
  • Singly Linked List
  • HashTable
  • Stack
  • Queue
  • String
  • Tree
  • Heap
  • Search

Algorithm

  • Sort
  • Recursive
  • Dynamic Programming
  • Greedy
  • Backtrack
  • Search
  • Random
  • Graph
  • Math
  • Geometric
  • NP
  • Bitwise

Floyd Warshall algorithm

The Floyd–Warshall algorithm compares many possible paths through the graph between each pair of vertices. It is guaranteed to find all shortest paths and is able to do this with $O(|V|^3)$ comparisons in a graph, even though there may be $O(|V|^2)$ edges in the graph. It does so by incrementally improving an estimate on the shortest path between two vertices, until the estimate is optimal.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
let dist be a |V| × |V| array of minimum distances initialized to  (infinity)
for each edge (u, v) do
    dist[u][v]  w(u, v)  // The weight of the edge (u, v)
for each vertex v do
    dist[v][v]  0
for k from 1 to |V|
    for i from 1 to |V|
        for j from 1 to |V|
            if dist[i][j] > dist[i][k] + dist[k][j]
                dist[i][j]  dist[i][k] + dist[k][j]
            end if
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution:
  def shortestPath(self, n, edges, maxD) -> int:
    graph = [[sys.maxsize]*n for _ in range(n)]
    for i,j,w in edges:
      graph[i][j] = w
    for i in range(n):
      graph[i][i] = 0

    for k in range(n):
      for i in range(n):
        for j in range(n):
          graph[i][j] = min(graph[i][j], graph[i][k] + graph[k][j])

    res = {sum(d <= maxD for d in graph[i]): for i in range(n)}

    return res[min(res)]

References

Licensed under CC BY-NC-SA 4.0
Get Things Done
Built with Hugo
Theme Stack designed by Jimmy