[关闭]
@Yano 2015-12-30T11:28:03.000000Z 字数 10468 阅读 9648

LeetCode之Breadth-first Search题目汇总

LeetCode

我的博客:http://blog.csdn.net/yano_nankai
LeetCode题解:https://github.com/LjyYano/LeetCode


LeetCode 题目汇总

LeetCode之Array题目汇总
LeetCode之Hash Table题目汇总
LeetCode之Linked List题目汇总
LeetCode之Math题目汇总
LeetCode之String题目汇总
LeetCode之Binary Search题目汇总
LeetCode之Divide and Conquer题目汇总
LeetCode之Dynamic Programming题目汇总
LeetCode之Backtracing题目汇总
LeetCode之Stack题目汇总
LeetCode之Sort题目汇总
LeetCode之Bit Manipulation题目汇总
LeetCode之Tree题目汇总
LeetCode之Depth-first Search题目汇总
LeetCode之Breadth-first Search题目汇总
LeetCode之Graph题目汇总
LeetCode之Trie题目汇总
LeetCode之Design题目汇总


文章目录:


Binary Tree Level Order Traversal

Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

For example:
Given binary tree {3,9,20,#,#,15,7},

  1. 3
  2. / \
  3. 9 20
  4. / \
  5. 15 7

return its level order traversal as:

  1. [
  2. [3],
  3. [9,20],
  4. [15,7]
  5. ]

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.


1. 通过统计每一行的结点数

定义两个变量,toBePrinted和nextLevel。

toBePrinted:当前待打印结点的数量  
nextLevel:下一层的结点数量

通过Deque来进行统计。


2. 插入特殊结点

参考自:Binary Tree Level Order Traversal

通过插入特殊结点,来判断一层是否结束。这样做的好处是不用统计每一层结点数目。伪代码如下:

a queue stores [step0, step1, step2, ...]

queue.add(first step)

while queue is not empty

  current_step = queue.poll()

  // do something here with current_step
  // like counting

  foreah step in current_step can jump to
    queue.add(step)

代码1:通过统计每一行的结点数:

  1. public List<List<Integer>> levelOrder(TreeNode root) {
  2. List<List<Integer>> rt = new ArrayList<List<Integer>>();
  3. if (root == null) {
  4. return rt;
  5. }
  6. Deque<TreeNode> deque = new LinkedList<TreeNode>();
  7. deque.add(root);
  8. int toBePrinted = 1;
  9. int nextLevel = 0;
  10. List<Integer> level = new LinkedList<Integer>();
  11. while (!deque.isEmpty()) {
  12. TreeNode p = deque.poll();
  13. level.add(p.val);
  14. toBePrinted--;
  15. if (p.left != null) {
  16. deque.addLast(p.left);
  17. nextLevel++;
  18. }
  19. if (p.right != null) {
  20. deque.addLast(p.right);
  21. nextLevel++;
  22. }
  23. if (toBePrinted == 0) {
  24. toBePrinted = nextLevel;
  25. nextLevel = 0;
  26. rt.add(new ArrayList<Integer>(level));
  27. level.clear();
  28. }
  29. }
  30. return rt;
  31. }

代码2:插入特殊结点:

  1. public List<List<Integer>> levelOrder2(TreeNode root) {
  2. List<List<Integer>> rt = new ArrayList<List<Integer>>();
  3. if (root == null) {
  4. return rt;
  5. }
  6. final TreeNode END = new TreeNode(0);
  7. Deque<TreeNode> deque = new LinkedList<TreeNode>();
  8. List<Integer> level = new LinkedList<Integer>();
  9. deque.add(root);
  10. deque.add(END);
  11. while (!deque.isEmpty()) {
  12. TreeNode p = deque.pop();
  13. if (p == END) {
  14. rt.add(new ArrayList<Integer>(level));
  15. level.clear();
  16. if (!deque.isEmpty()) {
  17. deque.add(END);
  18. }
  19. } else {
  20. level.add(p.val);
  21. if (p.left != null) {
  22. deque.add(p.left);
  23. }
  24. if (p.right != null) {
  25. deque.add(p.right);
  26. }
  27. }
  28. }
  29. return rt;
  30. }

Binary Tree Level Order Traversal II

Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).

For example:
Given binary tree {3,9,20,#,#,15,7},

  1. 3
  2. / \
  3. 9 20
  4. / \
  5. 15 7

return its bottom-up level order traversal as:

  1. [
  2. [15,7],
  3. [9,20],
  4. [3]
  5. ]

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.


参考:LeetCode 102 Binary Tree Level Order Traversal

只是在返回result前,加入一句话

  1. Collections.reverse(result);
  1. public List<List<Integer>> levelOrderBottom(TreeNode root) {
  2. List<List<Integer>> rt = new ArrayList<List<Integer>>();
  3. if (root == null) {
  4. return rt;
  5. }
  6. final TreeNode END = new TreeNode(0);
  7. Deque<TreeNode> deque = new LinkedList<TreeNode>();
  8. List<Integer> level = new LinkedList<Integer>();
  9. deque.add(root);
  10. deque.add(END);
  11. while (!deque.isEmpty()) {
  12. TreeNode p = deque.pop();
  13. if (p == END) {
  14. rt.add(new ArrayList<Integer>(level));
  15. level.clear();
  16. if (!deque.isEmpty()) {
  17. deque.add(END);
  18. }
  19. } else {
  20. level.add(p.val);
  21. if (p.left != null) {
  22. deque.add(p.left);
  23. }
  24. if (p.right != null) {
  25. deque.add(p.right);
  26. }
  27. }
  28. }
  29. Collections.reverse(rt);
  30. return rt;
  31. }

Binary Tree Zigzag Level Order Traversal

Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).

For example:
Given binary tree {3,9,20,#,#,15,7},

  1. 3
  2. / \
  3. 9 20
  4. / \
  5. 15 7

return its zigzag level order traversal as:

  1. [
  2. [3],
  3. [20,9],
  4. [15,7]
  5. ]

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.


参考LeetCode 102 Binary Tree Level Order Traversal

只需要加入一个变量,判断行数,翻转list即可。

  1. public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
  2. List<List<Integer>> rt = new ArrayList<List<Integer>>();
  3. if (root == null) {
  4. return rt;
  5. }
  6. final TreeNode END = new TreeNode(0);
  7. Deque<TreeNode> deque = new LinkedList<TreeNode>();
  8. List<Integer> level = new LinkedList<Integer>();
  9. int count = 0;
  10. deque.add(root);
  11. deque.add(END);
  12. while (!deque.isEmpty()) {
  13. TreeNode p = deque.pop();
  14. if (p == END) {
  15. if (count % 2 == 1) {
  16. Collections.reverse(level);
  17. }
  18. count++;
  19. rt.add(new ArrayList<Integer>(level));
  20. level.clear();
  21. if (!deque.isEmpty()) {
  22. deque.add(END);
  23. }
  24. } else {
  25. level.add(p.val);
  26. if (p.left != null) {
  27. deque.add(p.left);
  28. }
  29. if (p.right != null) {
  30. deque.add(p.right);
  31. }
  32. }
  33. }
  34. return rt;
  35. }

Course Schedule

There are a total of n courses you have to take, labeled from 0 to n - 1.

Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]

Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses?

For example:

2, [[1,0]]

There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible.

2, [[1,0],[0,1]]

There are a total of 2 courses to take. To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.

Note: 
The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.


题目等价为:检测图中是否有环

参考网址:LeetCode – Course Schedule (Java)

BFS:

  1. // BFS
  2. public static boolean canFinish(int numCourses, int[][] prerequisites) {
  3. // 参数检查
  4. if (prerequisites == null) {
  5. return false;
  6. }
  7. int len = prerequisites.length;
  8. if (numCourses <= 0 || len == 0) {
  9. return true;
  10. }
  11. // 记录每个course的prerequisites的数量
  12. int[] pCounter = new int[numCourses];
  13. for (int i = 0; i < len; i++) {
  14. pCounter[prerequisites[i][0]]++;
  15. }
  16. // 用队列记录可以直接访问的course
  17. LinkedList<Integer> queue = new LinkedList<Integer>();
  18. for (int i = 0; i < numCourses; i++) {
  19. if (pCounter[i] == 0) {
  20. queue.add(i);
  21. }
  22. }
  23. // 取出队列的course,判断
  24. int numNoPre = queue.size();
  25. while (!queue.isEmpty()) {
  26. int top = queue.remove();
  27. for (int i = 0; i < len; i++) {
  28. // 该course是某个course的prerequisites
  29. if (prerequisites[i][1] == top) {
  30. pCounter[prerequisites[i][0]]--;
  31. if (pCounter[prerequisites[i][0]] == 0) {
  32. numNoPre++;
  33. queue.add(prerequisites[i][0]);
  34. }
  35. }
  36. }
  37. }
  38. return numNoPre == numCourses;
  39. }

DFS:

  1. // DFS
  2. public static boolean canFinish2(int numCourses, int[][] prerequisites) {
  3. // 参数检查
  4. if (prerequisites == null) {
  5. return false;
  6. }
  7. int len = prerequisites.length;
  8. if (numCourses <= 0 || len == 0) {
  9. return true;
  10. }
  11. int[] visit = new int[numCourses];
  12. // key:course;value:以该course为prerequisites的course
  13. HashMap<Integer, ArrayList<Integer>> map = new HashMap<Integer, ArrayList<Integer>>();
  14. // 初始化map
  15. for (int[] p : prerequisites) {
  16. if (map.containsKey(p[1])) {
  17. map.get(p[1]).add(p[0]);
  18. } else {
  19. ArrayList<Integer> l = new ArrayList<Integer>();
  20. l.add(p[0]);
  21. map.put(p[1], l);
  22. }
  23. }
  24. // dfs
  25. for (int i = 0; i < numCourses; i++) {
  26. if (!canFinishDFS(map, visit, i)) {
  27. return false;
  28. }
  29. }
  30. return true;
  31. }
  32. private static boolean canFinishDFS(
  33. HashMap<Integer, ArrayList<Integer>> map, int[] visit, int i) {
  34. if (visit[i] == -1) {
  35. return false;
  36. }
  37. if (visit[i] == 1) {
  38. return true;
  39. }
  40. visit[i] = -1;
  41. // course i是某些course的prerequisites
  42. if (map.containsKey(i)) {
  43. for (int j : map.get(i)) {
  44. if (!canFinishDFS(map, visit, j)) {
  45. return false;
  46. }
  47. }
  48. }
  49. visit[i] = 1;
  50. return true;
  51. }

Course Schedule II

There are a total of n courses you have to take, labeled from 0 to n - 1.

Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]

Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you should take to finish all courses.

There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array.

For example:

2, [[1,0]]

There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1]

4, [[1,0],[2,0],[3,1],[3,2]]

There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0,1,2,3]. Another correct ordering is[0,2,1,3].

Note: 
The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.

click to show more hints.

Hints:

  1. This problem is equivalent to finding the topological order in a directed graph. If a cycle exists, no topological ordering exists and therefore it will be impossible to take all courses.
  2. Topological Sort via DFS - A great video tutorial (21 minutes) on Coursera explaining the basic concepts of Topological Sort.
  3. Topological sort could also be done via BFS.

参考:LeetCode 207 Course Schedule

只是加了一句话而已,用于保存结果。注意prerequisites为空的时候,任意输出一组结果即可。

  1. public int[] findOrder(int numCourses, int[][] prerequisites) {
  2. // 参数检查
  3. if (prerequisites == null) {
  4. throw new IllegalArgumentException();
  5. }
  6. int len = prerequisites.length;
  7. if (len == 0) {
  8. int[] seq = new int[numCourses];
  9. for (int i = 0; i < seq.length; i++) {
  10. seq[i] = i;
  11. }
  12. return seq;
  13. }
  14. int[] seq = new int[numCourses];
  15. int c = 0;
  16. // 记录每个course的prerequisites的数量
  17. int[] pCounter = new int[numCourses];
  18. for (int i = 0; i < len; i++) {
  19. pCounter[prerequisites[i][0]]++;
  20. }
  21. // 用队列记录可以直接访问的course
  22. LinkedList<Integer> queue = new LinkedList<Integer>();
  23. for (int i = 0; i < numCourses; i++) {
  24. if (pCounter[i] == 0) {
  25. queue.add(i);
  26. }
  27. }
  28. // 取出队列的course,判断
  29. int numNoPre = queue.size();
  30. while (!queue.isEmpty()) {
  31. int top = queue.remove();
  32. // 保存结果 +_+
  33. seq[c++] = top;
  34. for (int i = 0; i < len; i++) {
  35. // 该course是某个course的prerequisites
  36. if (prerequisites[i][1] == top) {
  37. pCounter[prerequisites[i][0]]--;
  38. if (pCounter[prerequisites[i][0]] == 0) {
  39. numNoPre++;
  40. queue.add(prerequisites[i][0]);
  41. }
  42. }
  43. }
  44. }
  45. if (numNoPre != numCourses) {
  46. return new int[] {};
  47. }
  48. return seq;
  49. }

Surrounded Regions

Given a 2D board containing 'X' and 'O', capture all regions surrounded by 'X'.

A region is captured by flipping all 'O's into 'X's in that surrounded region.

For example,

  1. X X X X
  2. X O O X
  3. X X O X
  4. X O X X

After running your function, the board should be:

  1. X X X X
  2. X X X X
  3. X X X X
  4. X O X X

和word search很像,但是应该首先找到没有被包围的O。

  1. static class Point {
  2. int x;
  3. int y;
  4. Point(int x, int y) {
  5. this.x = x;
  6. this.y = y;
  7. }
  8. }
  9. HashSet<String> boarderConnected;
  10. String pointId(int x, int y) {
  11. return x + "," + y;
  12. }
  13. boolean connectIfNotConnected(char[][] board, int x, int y) {
  14. if (x < 0 || y < 0)
  15. return false;
  16. if (x >= board.length || y >= board[0].length)
  17. return false;
  18. if (board[x][y] == 'X')
  19. return false;
  20. String id = pointId(x, y);
  21. if (boarderConnected.contains(id))
  22. return false;
  23. boarderConnected.add(id);
  24. return true;
  25. }
  26. void connectBoarder(char[][] board, int x, int y) {
  27. LinkedList<Point> queue = new LinkedList<Point>();
  28. queue.add(new Point(x, y));
  29. while (!queue.isEmpty()) {
  30. Point p = queue.poll();
  31. if (connectIfNotConnected(board, p.x, p.y)) {
  32. queue.add(new Point(p.x + 1, p.y));
  33. queue.add(new Point(p.x - 1, p.y));
  34. queue.add(new Point(p.x, p.y + 1));
  35. queue.add(new Point(p.x, p.y - 1));
  36. }
  37. }
  38. }
  39. public void solve(char[][] board) {
  40. int mx = board.length;
  41. if (mx < 3)
  42. return;
  43. int my = board[0].length;
  44. if (my < 3)
  45. return;
  46. boarderConnected = new HashSet<String>();
  47. int x;
  48. int y;
  49. for (x = 0; x < mx; x++) {
  50. connectBoarder(board, x, 0);
  51. connectBoarder(board, x, my - 1);
  52. }
  53. for (y = 0; y < my; y++) {
  54. connectBoarder(board, 0, y);
  55. connectBoarder(board, mx - 1, y);
  56. }
  57. for (x = 0; x < mx; x++) {
  58. for (y = 0; y < my; y++) {
  59. if (board[x][y] == 'O') {
  60. if (!boarderConnected.contains(pointId(x, y))) {
  61. board[x][y] = 'X';
  62. }
  63. }
  64. }
  65. }
  66. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注