BFS - 20190206
Posted lizzyluvcoding
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了BFS - 20190206相关的知识,希望对你有一定的参考价值。
1.二叉树 BFS
2.拓扑排序 重点 BFS
3.棋盘上的宽搜 BFS
图的遍历
层级遍历,由点及面,拓扑排序,简单图的最短路径
如果题目问最短路径:可能是BFS或者DP, 最长路径:DFS
queue 的数组实现
1.二叉树的BFS
https://www.lintcode.com/problem/binary-tree-level-order-traversal/description
1 /** 2 * Definition of TreeNode: 3 * public class TreeNode { 4 * public int val; 5 * public TreeNode left, right; 6 * public TreeNode(int val) { 7 * this.val = val; 8 * this.left = this.right = null; 9 * } 10 * } 11 */ 12 13 public class Solution { 14 /** 15 * @param root: A Tree 16 * @return: Level order a list of lists of integer 17 */ 18 public List<List<Integer>> levelOrder(TreeNode root) { 19 // write your code here 20 List<List<Integer>> results = new ArrayList<>(); 21 if(root == null){ 22 return results; 23 } 24 //interface offer(add) poll(pop) 25 Queue<TreeNode> queue = new LinkedList<>(); 26 //put start node into queue 27 queue.offer(root); 28 29 while(!queue.isEmpty()){ 30 //lever x->x+1 31 ArrayList<Integer> currentLevel = new ArrayList(); 32 int size = queue.size(); 33 for(int i =0; i<size;i++){ 34 TreeNode head = queue.poll(); 35 currentLevel.add(head.val); 36 if(head.left != null){ 37 queue.offer(head.left); 38 } 39 if(head.right != null){ 40 queue.offer(head.right); 41 } 42 } 43 results.add(currentLevel); 44 } 45 46 return results; 47 48 49 } 50 }
queue, offer 和 add的区别
序列化:
xml json thrift(by facebook) protobuf(by google)
序列化算法设计时需要考虑的因素:压缩率 thrift protobuf是为了更快的传输数据和节省存储空间而设计的
可读性:如json
https://www.lintcode.com/problem/graph-valid-tree/description
1 public class Solution { 2 /** 3 * @param n: An integer 4 * @param edges: a list of undirected edges 5 * @return: true if it‘s a valid tree, or false 6 */ 7 public boolean validTree(int n, int[][] edges) { 8 // write your code here 9 if(n==0){ 10 return false; 11 } 12 13 if(edges.length != n-1){ 14 return false; 15 } 16 //adjacent lists 17 Map<Integer,Set<Integer>> graph = initializeGraph(n,edges); 18 19 Queue<Integer> queue = new LinkedList<>(); 20 Set<Integer> hash = new HashSet<>(); 21 22 queue.offer(0); 23 hash.add(0); 24 25 while(!queue.isEmpty()){ 26 int node = queue.poll(); 27 for(Integer neigh:graph.get(node)){ 28 if(hash.contains(neigh)){ 29 continue; 30 } 31 hash.add(neigh); 32 queue.offer(neigh); 33 } 34 } 35 return hash.size()==n; 36 37 } 38 39 private Map<Integer,Set<Integer>> initializeGraph(int n,int[][]edges){ 40 Map<Integer,Set<Integer>> graph = new HashMap<>(); 41 for(int i=0;i<n;i++){ 42 graph.put(i,new HashSet<>()); 43 } 44 for(int i =0;i<edges.length;i++){ 45 int u = edges[i][0]; 46 int v = edges[i][1]; 47 graph.get(u).add(v); 48 graph.get(v).add(u); 49 } 50 return graph; 51 } 52 }
以上是关于BFS - 20190206的主要内容,如果未能解决你的问题,请参考以下文章
HDU3247 Resource Archiver(AC自动机+BFS+DP)
[bfs] aw1107. 魔板(bfs最小步数模型+代码细节+代码功底+好题)