Algorithm
Topological Sort
Dijkstra’s Algorithm
- Dijkstra’s algorithm is an algorithm for finding the shortest paths between nodes in a graph,
- Dijkstra is a special case for A* (when the heuristics is zero)
- It has one cost function, which is real cost value from source to each node: f(x)=g(x). It finds the shortest path from source to every other node by considering only real cost.
A* search:
|
|
- Time: O(E + V * log(V))
- For dense graph where E ~ V^2
Python + heapq implementation
12345678910111213141516171819202122232425262728293031323334353637383940# https://gist.github.com/kachayev/5990802from collections import defaultdictfrom heapq import *def dijkstra(edges, f, t):g = defaultdict(list)for l,r,c in edges:g[l].append((c,r))q, seen = [(0,f,[])], set()while q:(cost,v1,path) = heappop(q)if v1 not in seen:seen.add(v1)path = path + [v1]if v1 == t: return (cost, path)for c2, v2 in g.get(v1, ()):if v2 not in seen:heappush(q, (cost+c2, v2, path))return float("inf")if __name__ == "__main__":edges = [("A", "B", 7),("A", "D", 5),("B", "C", 8),("B", "D", 9),("B", "E", 7),("C", "E", 5),("D", "E", 15),("D", "F", 6),("E", "F", 8),("E", "G", 9),("F", "G", 11)]print "A -> E:"print dijkstra(edges, "A", "E")print "F -> G:"print dijkstra(edges, "F", "G")
- For dense graph where E ~ V^2
exercises
https://leetcode.com/problems/cheapest-flights-within-k-stops/description/
A* search
A* is an informed search algorithm, or a best-first search, meaning that it solves problems by searching among all possible paths to the solution (goal) for the one that incurs the smallest cost (least distance travelled, shortest time, etc.), and among these paths it first considers the ones that appear to lead most quickly to the solution
It has two cost function.
- g(x): same as Dijkstra. The real cost to reach a node x.
- h(x): approximate cost from node x to goal node. It is a heuristic function. This heuristic function should never overestimate the cost. That means, the real cost to reach goal node from node x should be greater than or equal h(x). It is called admissible heuristic.
- The total cost of each node is calculated by f(x)=g(x)+h(x)
References: https://stackoverflow.com/questions/1332466/how-does-dijkstras-algorithm-and-a-star-compare
Eulerian path
e.g.
https://leetcode.com/problems/reconstruct-itinerary/discuss/78768/Short-Ruby-Python-Java-C++
Hamiltonian path
a Hamiltonian path (or traceable path) is a path in an undirected or directed graph that visits each vertex exactly once. A Hamiltonian cycle (or Hamiltonian circuit) is a Hamiltonian path that is a cycle
AVL Tree
Red Black Tree
Binary Index Tree
Segement Tree
Design
KMP
关于kmp算法,讲的最好的当属阮一峰的字符串匹配的KMP算法
|
|