├── AlgorithmDiagram.pdf ├── LICENSE ├── README.md ├── chapter1 ├── BinarySearchExample.txt ├── Hcjcch_BinarySearch.kt ├── Link_BinarySearch.cpp ├── ZHW_BinarySearch.java └── ZHW_binary_search.py ├── chapter10 └── ZHW_demo.py ├── chapter11 └── ZHW_demo.py ├── chapter12 └── ZHW_demo.py ├── chapter2 ├── Link_SelectSort.cpp ├── SelectSort_others.py ├── ZHW_SelectSort.java ├── ZHW_SelectSort.py ├── c++_selectsort.png ├── java_selectsort.png ├── python_selectsort.png ├── 时间复杂度练习题.md └── 选择排序练习题.md ├── chapter3 ├── Link_Factorial.cpp ├── ZHW_Factorial.java ├── ZHW_Factorial.py ├── c++_factorial.png ├── java_factorial.png ├── python_fatorial.png └── 递归练习题.md ├── chapter4 ├── Link_QuickSort.cpp ├── ZHW_QuickSort.java ├── ZHW_QuickSort.py ├── c++_quicksort.png ├── java_quicksort.png ├── python_quicksort.png └── 面试技巧.md ├── chapter5 └── ZHW_demo.py ├── chapter6 ├── Link_SearchQueue.java ├── ZHW_SearchQueue.py ├── java_searchqueue.png └── python_searchqueue.png ├── chapter7 ├── Link_LowestCost.java ├── ZHW_LowestCost.py ├── java_lost_cost.png └── python_lost_cost.png ├── chapter8 ├── Link_np.java ├── ZHW_np.py ├── java_np.png └── python_np.jpg ├── chapter9 └── ZHW_demo.py └── images ├── .DS_Store └── algorithmdiagram.jpg /AlgorithmDiagram.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhanwen/AlgorithmDiagram/ffbd16b296330f47a80032d6ada2aeb0bd08c266/AlgorithmDiagram.pdf -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 hanwen 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # AlgorithmDiagram 2 | 算法图解的算法代码示例,用Python和Java实现,后期会加入其它语言。 3 | 也欢迎用其它语言来实现,那就在好不过了。 4 |
5 | 6 | ### 《算法图解》阅读计划     7 | 8 | #### 算法群阅读计划(第1期) 9 | 10 | **领读人:张旱文** 11 | 12 | **本书特色**   13 | 14 | - 你渴望像看喜欢的小说一样学习算法吗?如果是,这本书正是你梦寐以求的! 15 | - 算法学习起来一点都不乏味!这本书既活泼有趣又富有洞见。 16 | - 这本书完成了一项不可能完成的任务:让数学变得有趣而易懂! 17 | 18 | **适合读者** 19 | 20 | - 业余程序员、编程培训班学员、需要重温算法的计算机专业毕业生、对编程感兴趣的物理或数学等专业毕业生。 21 | 22 | **答疑时间安排** 23 | 24 | - 每周一次,周六晚上8点到10点 25 | 26 | **欢迎读者们来图灵读者小密圈打卡、贴图、发疑问** 27 | 28 | **总跨度** 29 | 30 | - 一个月    31 | 32 | **每天阅读用时** 33 | 34 | * 2小时(建议多做练习)   35 | 36 | **读前须知**    37 | 38 | - 我会将书中的算法用Python和Java两种语言实现。(Python是书中使用的语言),也欢迎用其它语言来实现,那就更好了。 39 | 40 | - 方便记录我们的练习,我在github创建了一个仓库,大家可以把每天的练习进行PR。(要保证程序是AC的才行哦),这样才有参考的价值,大家可以对不同的实现来进行讨论。   41 | 42 | - **仓库地址:**[https://github.com/zhanwen/AlgorithmDiagram][1] 43 | 44 | - 目录我已创建完成。这里为了方便记录和区分。大家在PR的时候,建议文件命名规则为:作者姓名英文缩写+文件名。在chapter1中已有示例。 45 | 46 | - 在练习的过程中,我也会找一些书中相关的算法题目,让大家一起来练习。 47 | 48 | # 阅读划分 49 | 50 | **一、第一部分(1-7章)** 51 | 52 | **阅读时长:1-2 周** 53 | 54 | **重点部分** 55 | 56 |   1. 二分查找(掌握) 以最常见的例子查电话簿引入第一个算法,可以明显感觉到使用不同的算法,带来的性能上和时间上的提升。 57 | 58 |   2. 大O表示法(掌握) 为了能够比较各种算法之间的运行时间,要有一个可以衡量的点。 59 | 60 |   3. 内存的工作原理 (理解) 61 | 62 |   4. 数组和链表 (理解) 63 | 64 |   5. 选择排序 (掌握) 65 | 66 |   6. 快速排序(掌握) 67 | 68 | 69 | **难点部分** 70 | 71 |   1. 递归(掌握) 72 | 73 |   2. 散列表(掌握) 74 | 75 |   3. 图(理解并掌握)   76 | 77 | 78 | **二、第二部分(8-11章)** 79 | 80 | **阅读时长:3-4 周**     81 | 82 | **重点部分** 83 | 84 |   1. 贪婪算法 (背包问题)(理解掌握) 85 | 86 |   2. 动态规划(理解掌握) 87 | 88 |   3. K最近邻算法(理解掌握) 89 | 90 | 91 | **难点部分(理解)** 92 | 93 |   1. 树 94 | 95 |   2. 傅里叶变换  96 | 97 |   3. 并行算法 98 | 99 |   4. MapReduce 100 | 101 |   5. 反向索引 102 | 103 |   6. 布隆过滤器 104 | 105 |   7. SHA算法 106 | 107 |   8. 局部敏感的散列算法 108 | 109 |   9. Diffie-Hellman密钥交换 110 | 111 |   10. 线性交换 112 | 113 | **其他建议** 114 | 115 | - 第一部分内容计划是两个星期以内要完成,看的快的同学可能一个星期就完成了,这里大家可以自己安排。 116 | 117 | - 第二部分内容计划在剩余的时间内完成。最重要的是大家一定要自己将算法写出来并能运行,才会有更多的收获。 118 | 119 | 120 | ### 想提高自己的技术和认知 121 | 122 | 123 | 124 | [1]: https://github.com/zhanwen/AlgorithmDiagram 125 | 126 | 127 | 128 | -------------------------------------------------------------------------------- /chapter1/BinarySearchExample.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhanwen/AlgorithmDiagram/ffbd16b296330f47a80032d6ada2aeb0bd08c266/chapter1/BinarySearchExample.txt -------------------------------------------------------------------------------- /chapter1/Hcjcch_BinarySearch.kt: -------------------------------------------------------------------------------- 1 | package com.hcjcch.datastructure 2 | 3 | /** 4 | * BinarySearch 5 | * 6 | * @author huangchen 7 | * @date 2018/1/2 8 | */ 9 | fun main(args: Array) { 10 | println(binarySearch(listOf(1, 3, 5, 7, 9, 13, 14, 17, 19), 6)) 11 | println(binarySearch(listOf(1, 3, 5, 7, 9, 13, 14, 17, 19), 13)) 12 | println(binarySearch(listOf(1, 3, 5, 7, 9, 13, 14, 17, 19), 29)) 13 | } 14 | 15 | /** 16 | * 二分搜索 17 | * 18 | * @param list 已排序的数组 19 | * @param target 待查询的目标值 20 | * @return 目标值在列表中的索引,从0开始,未查询到时返回-1 21 | */ 22 | fun binarySearch(list: List, target: Int): Int { 23 | var lowIndex = 0 24 | var highIndex = list.size - 1 25 | while (lowIndex <= highIndex) { 26 | val middle = (lowIndex + highIndex) / 2 27 | val guess = list[middle] 28 | when { 29 | guess == target -> return middle 30 | guess < target -> lowIndex = middle + 1 31 | else -> highIndex = middle - 1 32 | } 33 | } 34 | return -1 35 | } -------------------------------------------------------------------------------- /chapter1/Link_BinarySearch.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | int main() { 6 | int arr[5] = {1,2,3,4,5}; 7 | int item = 2; 8 | 9 | int arrayLen = sizeof(arr)/sizeof(arr[0]); 10 | int low = 0; 11 | int high = arrayLen - 1; 12 | int result = -1; 13 | 14 | while (low <= high) { 15 | int mid = (low + high) / 2; 16 | if (item == arr[mid]){ 17 | cout< item: 13 | high = mid - 1 14 | else: 15 | low = mid + 1 16 | return -1 17 | 18 | 19 | list = [1, 2, 3, 4, 5, 6, 7] 20 | 21 | # 能找到对应的值 22 | print binary_search(list, 3) 23 | print binary_search(list, 6) 24 | 25 | # 不能找到对应的值 26 | print binary_search(list, 8) 27 | -------------------------------------------------------------------------------- /chapter10/ZHW_demo.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhanwen/AlgorithmDiagram/ffbd16b296330f47a80032d6ada2aeb0bd08c266/chapter10/ZHW_demo.py -------------------------------------------------------------------------------- /chapter11/ZHW_demo.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhanwen/AlgorithmDiagram/ffbd16b296330f47a80032d6ada2aeb0bd08c266/chapter11/ZHW_demo.py -------------------------------------------------------------------------------- /chapter12/ZHW_demo.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhanwen/AlgorithmDiagram/ffbd16b296330f47a80032d6ada2aeb0bd08c266/chapter12/ZHW_demo.py -------------------------------------------------------------------------------- /chapter2/Link_SelectSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int arr[10] = {1,4,5,8,9,6,2,3,7,10}; 7 | 8 | int length = sizeof(arr)/sizeof(arr[0]); 9 | for(int i = 0; i < length; i++) { 10 | for(int j = i+1; j < length; j++) { 11 | if(arr[i] > arr[j]) { 12 | int temp = arr[j]; 13 | arr[j] = arr[i]; 14 | arr[i] = temp; 15 | } 16 | } 17 | } 18 | 19 | for(int i = 0; i < length; i++) { 20 | cout< arr[j]: 14 | arr[i], arr[j] = arr[j], arr[i] 15 | return arr 16 | 17 | if __name__ == '__main__': 18 | array = [4, 2, 5, 6, 7, 9, 1, 8, 3, 10] 19 | print(select_sort(array)) 20 | -------------------------------------------------------------------------------- /chapter2/ZHW_SelectSort.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * @author Hanwen 4 | * @date 2017年8月28日 下午5:45:48 5 | * @version 6 | */ 7 | public class SelectSort { 8 | public static void main(String[] args) { 9 | int[] array = new int[]{1,4,5,8,9,6,2,3,7,10}; 10 | int[] result = findMinNumber(array); 11 | for(int i = 0; i < result.length; i++) { 12 | System.out.print(result[i]+ " "); 13 | } 14 | } 15 | 16 | /** 17 | * 选择排序 18 | * @param array 数组 19 | * @return 排序好的数组(从小到大) 20 | */ 21 | private static int[] findMinNumber(int[] array) { 22 | for(int i = 0; i < array.length; i++) { 23 | for(int j = i+1; j < array.length; j++) { 24 | if(array[i] > array[j]) { 25 | int temp = array[j]; 26 | array[j] = array[i]; 27 | array[i] = temp; 28 | } 29 | } 30 | } 31 | return array; 32 | } 33 | } -------------------------------------------------------------------------------- /chapter2/ZHW_SelectSort.py: -------------------------------------------------------------------------------- 1 | #查找数组中的最小数的索引 2 | def findMinNumber(array) : 3 | min = array[0] 4 | min_index = 0 5 | for i in range(1, len(array)) : 6 | if array[i] < min : 7 | min = array[i] 8 | min_index = i 9 | return min_index 10 | 11 | 12 | #选择排序 13 | def selectSort(array) : 14 | newArray = [] 15 | for i in range(len(array)) : 16 | min = findMinNumber(array) 17 | newArray.append(array.pop(min)) 18 | return newArray 19 | 20 | print(selectSort([4,2,5,6,7,9,1,8,3,10])) -------------------------------------------------------------------------------- /chapter2/c++_selectsort.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhanwen/AlgorithmDiagram/ffbd16b296330f47a80032d6ada2aeb0bd08c266/chapter2/c++_selectsort.png -------------------------------------------------------------------------------- /chapter2/java_selectsort.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhanwen/AlgorithmDiagram/ffbd16b296330f47a80032d6ada2aeb0bd08c266/chapter2/java_selectsort.png -------------------------------------------------------------------------------- /chapter2/python_selectsort.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhanwen/AlgorithmDiagram/ffbd16b296330f47a80032d6ada2aeb0bd08c266/chapter2/python_selectsort.png -------------------------------------------------------------------------------- /chapter2/时间复杂度练习题.md: -------------------------------------------------------------------------------- 1 | # 练习一 2 | 请使用任意算法,完成下面的计算,要求时间复杂读为(N^2) 3 | 4 | 1 + 2 + 3 + …… + N 5 | -------------------------------------------------------------------------------- /chapter2/选择排序练习题.md: -------------------------------------------------------------------------------- 1 | 选择排序的思想 2 | 3 | 1. 每一次从待排序的数据元素中选出最小(或最大)的一个元素,存放在序列的起始位置 4 | 2. 直到全部待排序的数据元素排完 5 | 6 | 选择排序的方法实现下面的操作 7 | 8 | 1. 降序排列 9 | 2. 升序排列 10 | 11 | 练习 12 | 对任意十个数进行排序,并计算出相应的时间复杂度和空间复杂度 13 | -------------------------------------------------------------------------------- /chapter3/Link_Factorial.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int factorial(int n) { 5 | if(n == 1) { 6 | return 1; 7 | }else { 8 | return n * factorial(n-1); 9 | } 10 | } 11 | 12 | int main() 13 | { 14 | cout< 2 | using namespace std; 3 | 4 | //找出基准元的下标,并且完成元素的分块 5 | //找出基准元的方法很多,取第一个或者最后一个都不是一个好方法 6 | //具体可以自行上网查阅资料 7 | int Sort(int arr[], int left, int right) { 8 | //取第一个元素为基准元 9 | int pivotValue = arr[left]; 10 | 11 | //使用双向扫描法完成分块 12 | //基准元的左边都小于他,右边都大于他 13 | while (left < right) { 14 | while (left < right && arr[right] >= pivotValue) { 15 | right--; 16 | } 17 | arr[left] = arr[right]; 18 | while(left < right && arr[left] <= pivotValue) { 19 | left++; 20 | } 21 | arr[right] = arr[left]; 22 | } 23 | arr[left] = pivotValue; 24 | return left; 25 | } 26 | 27 | int quickSort(int arr[], int left, int right) { 28 | if (left < right) 29 | { 30 | //分块后基准元的下标 31 | int pivot = Sort(arr, left, right); 32 | //对分块后的部分进行排序 33 | quickSort(arr, left, pivot - 1); 34 | quickSort(arr, pivot + 1, right); 35 | } 36 | } 37 | 38 | int main() 39 | { 40 | int arr[10] = {1,4,5,8,9,6,2,3,7,10}; 41 | int length = sizeof(arr)/sizeof(int); 42 | quickSort(arr, 0, length-1); 43 | 44 | for(int i = 0; i < length; i++) { 45 | cout< pivot] 8 | return quicksort(less) + [pivot] + quicksort(greate) 9 | 10 | 11 | array = [1,5,2,3,7,6] 12 | 13 | print(quicksort(array)) -------------------------------------------------------------------------------- /chapter4/c++_quicksort.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhanwen/AlgorithmDiagram/ffbd16b296330f47a80032d6ada2aeb0bd08c266/chapter4/c++_quicksort.png -------------------------------------------------------------------------------- /chapter4/java_quicksort.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhanwen/AlgorithmDiagram/ffbd16b296330f47a80032d6ada2aeb0bd08c266/chapter4/java_quicksort.png -------------------------------------------------------------------------------- /chapter4/python_quicksort.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhanwen/AlgorithmDiagram/ffbd16b296330f47a80032d6ada2aeb0bd08c266/chapter4/python_quicksort.png -------------------------------------------------------------------------------- /chapter4/面试技巧.md: -------------------------------------------------------------------------------- 1 | #### 快速排序是面试中经常出现的算法题。一般面试官会要求在纸上写代码,所以我们平常不要漠视常见算法的实现,因为这能考查编程基本功。 2 | -------------------------------------------------------------------------------- /chapter5/ZHW_demo.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhanwen/AlgorithmDiagram/ffbd16b296330f47a80032d6ada2aeb0bd08c266/chapter5/ZHW_demo.py -------------------------------------------------------------------------------- /chapter6/Link_SearchQueue.java: -------------------------------------------------------------------------------- 1 | public class searchQueue{ 2 | 3 | //使用二维数组表示有向图 4 | static String[] graphName = {"you","alice","bob","claire","anuj","peggy","thom","jonny"}; 5 | static String[][] graph = { 6 | {"you","alice"}, 7 | {"you","bob"}, 8 | {"you","claire"}, 9 | {"bob","anuj"}, 10 | {"bob","peggy"}, 11 | {"alice","peggy"}, 12 | {"claire","thom"}, 13 | {"claire","jonny"}, 14 | 15 | }; 16 | 17 | 18 | public static boolean Search(String name){ 19 | Queue searchQueue = new LinkedList<>(); 20 | Queue searched = new LinkedList<>(); 21 | for (int i = 0; i < graphName.length; i++) 22 | searchQueue.add(graphName[i]); 23 | 24 | while (!searchQueue.isEmpty()) { 25 | String person = searchQueue.poll(); 26 | if(!searched.contains(person)) { 27 | if(personIsSeller(person)) { 28 | System.out.println(person + " is a mango seller!"); 29 | return true; 30 | }else { 31 | for (int i = 0; i < graph.length; i++) { 32 | if (graph[i][0].equals(person)) 33 | searchQueue.add(graph[i][1]); 34 | } 35 | searched.add(person); 36 | } 37 | } 38 | } 39 | return false; 40 | } 41 | 42 | 43 | public static boolean personIsSeller(String name){ 44 | return name.charAt(name.length()-1) == 'm'; 45 | } 46 | 47 | 48 | public static void main(String[] args) { 49 | System.out.println(Search("you")); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /chapter6/ZHW_SearchQueue.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | graph = {} 4 | graph["you"] = ["alice", "bob", "claire"] 5 | graph["bob"] = ["anuj", "peggy"] 6 | graph["alice"] = ["peggy"] 7 | graph["claire"] = ["thom", "jonny"] 8 | graph["anuj"] = [] 9 | graph["peggy"] = [] 10 | graph["thom"] = [] 11 | graph["jonny"] = [] 12 | 13 | def search(name) : 14 | search_queue = deque() 15 | search_queue += graph[name] 16 | searched = [] 17 | while search_queue : 18 | person = search_queue.popleft() 19 | if person not in searched : 20 | if person_is_seller(person) : 21 | print("Person " + person +"is a mango seller") 22 | return True 23 | else : 24 | search_queue += graph[person] 25 | searched.append(person) 26 | return False 27 | 28 | 29 | def person_is_seller(name) : 30 | return name[-1] == 'm' 31 | 32 | print(search('you')) -------------------------------------------------------------------------------- /chapter6/java_searchqueue.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhanwen/AlgorithmDiagram/ffbd16b296330f47a80032d6ada2aeb0bd08c266/chapter6/java_searchqueue.png -------------------------------------------------------------------------------- /chapter6/python_searchqueue.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhanwen/AlgorithmDiagram/ffbd16b296330f47a80032d6ada2aeb0bd08c266/chapter6/python_searchqueue.png -------------------------------------------------------------------------------- /chapter7/Link_LowestCost.java: -------------------------------------------------------------------------------- 1 | public class LowestCost{ 2 | 3 | //不可达记为INF 4 | //不可记为Integer.MAX_VALUE,再加cost会变成负数,影响结果 5 | final static int INF = 999999; 6 | 7 | //下标与名称的映射 8 | static Map map = new HashMap<>(); 9 | 10 | //用二位数组邻接矩阵表示有向加权图,下标表示边,值表示权 11 | //以行为边的起点,列为边的终点 12 | //INF表示不可达 13 | static int[][] graph = { 14 | {INF,6,2,INF}, 15 | {INF,INF,INF,1}, 16 | {INF,3,INF,5}, 17 | {INF,INF,INF,INF} 18 | }; 19 | 20 | static int[] costs = { 21 | INF, //start 22 | 6, //A 23 | 2, //B 24 | INF //end 25 | }; 26 | 27 | static int[] parents = { 28 | INF, //start 的起点 29 | 0, //A的起点 30 | 0, //B的起点 31 | -1 //end的起点 32 | }; 33 | 34 | //记录是否处理过,处理过 记为1 35 | static int[] proceessed = { 36 | 0, 37 | 0, 38 | 0, 39 | 0 40 | }; 41 | 42 | public static void main(String[] args) { 43 | map.put(0,"start"); 44 | map.put(1,"A"); 45 | map.put(2,"B"); 46 | map.put(3,"end"); 47 | 48 | int node = findLowestCostNode(costs); 49 | while (node != 0) { 50 | int cost = costs[node]; 51 | 52 | for (int i = 0; i < graph[node].length; i++) { 53 | int newCost = cost + graph[node][i]; 54 | if (costs[i] > newCost){ 55 | costs[i] = newCost; 56 | parents[i] = node; 57 | } 58 | } 59 | proceessed[node] = 1; 60 | node = findLowestCostNode(costs); 61 | } 62 | 63 | //最终输出parents表,即可得出花费最少路线 64 | for (int i = 0; i < parents.length; i++) { 65 | System.out.print(map.get(i)+" "); 66 | System.out.println(map.get(parents[i])); 67 | 68 | } 69 | 70 | } 71 | 72 | //返回花费最少的节点(下标) 73 | public static int findLowestCostNode(int[] costs) { 74 | int lowCost = Integer.MAX_VALUE; 75 | int lowCostNode = 0; 76 | for (int i = 0; i < costs.length; i++) { 77 | int cost = costs[i]; 78 | if (cost < lowCost && proceessed[i] == 0) { 79 | lowCost = cost; 80 | lowCostNode = i; 81 | } 82 | } 83 | return lowCostNode; 84 | } 85 | 86 | } -------------------------------------------------------------------------------- /chapter7/ZHW_LowestCost.py: -------------------------------------------------------------------------------- 1 | graph = {} 2 | graph["start"] = {} 3 | graph["start"]["a"] = 6 4 | graph["start"]["b"] = 2 5 | 6 | graph["a"] = {} 7 | graph["a"]["finish"] = 1; 8 | 9 | graph["b"] = {} 10 | graph["b"]["a"] = 3 11 | graph["b"]["finish"] = 5 12 | 13 | graph["finish"] = {} 14 | 15 | infinity = float("inf") 16 | costs = {} 17 | costs["a"] = 6 18 | costs["b"] = 2 19 | costs["finish"] = infinity 20 | 21 | parents = {} 22 | 23 | parents["a"] = "start" 24 | parents["b"] = "start" 25 | parents["finish"] = "None" 26 | 27 | processed = [] 28 | print(costs) 29 | def find_lowest_cost_node(costs) : 30 | low_costs = float("inf") 31 | low_costs_node = None 32 | for node in costs : 33 | cost = costs[node] 34 | if cost < low_costs and node not in processed : 35 | low_costs = cost 36 | low_costs_node = node 37 | return low_costs_node 38 | 39 | node = find_lowest_cost_node(costs) 40 | while node is not None : 41 | cost = costs[node] 42 | neighbors = graph[node] 43 | for n in neighbors.keys() : 44 | new_cost = cost + neighbors[n] 45 | if costs[n] > new_cost: 46 | costs[n] = new_cost 47 | parents[n] = node 48 | processed.append(node) 49 | node = find_lowest_cost_node(costs) 50 | 51 | print(costs) -------------------------------------------------------------------------------- /chapter7/java_lost_cost.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhanwen/AlgorithmDiagram/ffbd16b296330f47a80032d6ada2aeb0bd08c266/chapter7/java_lost_cost.png -------------------------------------------------------------------------------- /chapter7/python_lost_cost.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhanwen/AlgorithmDiagram/ffbd16b296330f47a80032d6ada2aeb0bd08c266/chapter7/python_lost_cost.png -------------------------------------------------------------------------------- /chapter8/Link_np.java: -------------------------------------------------------------------------------- 1 | public class Main{ 2 | 3 | static Set statesNeeds = new HashSet<>(); 4 | static String[] str = {"mt", "wa", "or", "id", "nv", "ut", "ca", "az"}; 5 | 6 | static Map> stations = new HashMap<>(); 7 | 8 | //初始化 9 | public static void Init(){ 10 | //需要覆盖的州 11 | for (int i = 0; i < str.length; i++) { 12 | statesNeeds.add(str[i]); 13 | } 14 | 15 | //广播站 16 | Set temp = new HashSet<>(); 17 | temp.add("id"); 18 | temp.add("nv"); 19 | temp.add("ut"); 20 | stations.put("kone", temp); 21 | 22 | Set temp1 = new HashSet<>(); 23 | temp1.add("wa"); 24 | temp1.add("id"); 25 | temp1.add("mt"); 26 | stations.put("ktwo", temp1); 27 | 28 | Set temp2 = new HashSet<>(); 29 | temp2.add("or"); 30 | temp2.add("nv"); 31 | temp2.add("ca"); 32 | stations.put("kthree", temp2); 33 | 34 | Set temp3 = new HashSet<>(); 35 | temp3.add("nv"); 36 | temp3.add("ut"); 37 | stations.put("kfour", temp3); 38 | 39 | Set temp4 = new HashSet<>(); 40 | temp4.add("ca"); 41 | temp4.add("az"); 42 | stations.put("kfive", temp4); 43 | 44 | //System.out.println(stations); 45 | } 46 | 47 | public static void main(String[] args) { 48 | 49 | Init(); 50 | 51 | List finalStations = new LinkedList<>(); 52 | 53 | while (statesNeeds.size()!=0) { 54 | Set states_covered = new HashSet<>(); 55 | String best_stations = null; 56 | 57 | for (Map.Entry> entry : stations.entrySet()) { 58 | Set states_for_station = entry.getValue(); 59 | states_for_station.retainAll(statesNeeds); //交集 covered 60 | 61 | if (states_covered.size() < states_for_station.size()){ 62 | best_stations = entry.getKey(); 63 | states_covered = states_for_station; 64 | } 65 | } 66 | statesNeeds.removeAll(states_covered); 67 | finalStations.add(best_stations); 68 | 69 | } 70 | 71 | //结果为1.2.3.5 或者 2.3.4.5 72 | System.out.println(finalStations); 73 | } 74 | 75 | } -------------------------------------------------------------------------------- /chapter8/ZHW_np.py: -------------------------------------------------------------------------------- 1 | #需要覆盖的州 2 | states_needs = set(['mt', 'wa', 'or', 'id', 'nv', 'ut', 'ca', 'az']) 3 | 4 | #广播站 5 | stations = {} 6 | stations['kone'] = set(['id', 'nv', 'ut']) 7 | stations['ktwo'] = set(['wa', 'id', 'mt']) 8 | stations['kthree'] = set(['or', 'nv', 'ca']) 9 | stations['kfour'] = set(['nv', 'ut']) 10 | stations['kfive'] = set(['ca', 'az']) 11 | 12 | 13 | final_stations = set() 14 | 15 | while states_needs : 16 | best_stations = None 17 | # 覆盖的州 18 | states_covered = set() 19 | #key,value 20 | for station, states_for_station in stations.items() : 21 | convered = states_needs & states_for_station 22 | if(len(convered) > len(states_covered)) : 23 | best_stations = station 24 | states_covered = convered 25 | states_needs -= states_covered 26 | final_stations.add(best_stations) 27 | 28 | print(final_stations) -------------------------------------------------------------------------------- /chapter8/java_np.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhanwen/AlgorithmDiagram/ffbd16b296330f47a80032d6ada2aeb0bd08c266/chapter8/java_np.png -------------------------------------------------------------------------------- /chapter8/python_np.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhanwen/AlgorithmDiagram/ffbd16b296330f47a80032d6ada2aeb0bd08c266/chapter8/python_np.jpg -------------------------------------------------------------------------------- /chapter9/ZHW_demo.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhanwen/AlgorithmDiagram/ffbd16b296330f47a80032d6ada2aeb0bd08c266/chapter9/ZHW_demo.py -------------------------------------------------------------------------------- /images/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhanwen/AlgorithmDiagram/ffbd16b296330f47a80032d6ada2aeb0bd08c266/images/.DS_Store -------------------------------------------------------------------------------- /images/algorithmdiagram.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhanwen/AlgorithmDiagram/ffbd16b296330f47a80032d6ada2aeb0bd08c266/images/algorithmdiagram.jpg --------------------------------------------------------------------------------