1.png
2.png

广度搜索

先上代码

  1. class Solution {
  2. int[] dx = {1, 0, 0, -1};
  3. int[] dy = {0, 1, -1, 0};//后面广搜用来遍历这俩然后遍历上下左右用的
  4. public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
  5. int currColor = image[sr][sc];//
  6. if (currColor == newColor) {
  7. return image;
  8. }//如果已经是了就原样返回
  9. int n = image.length, m = image[0].length;//长度和行长度
  10. Queue<int[]> queue = new LinkedList<int[]>();
  11. queue.offer(new int[]{sr, sc});//插入
  12. image[sr][sc] = newColor;
  13. //用队列
  14. while (!queue.isEmpty()) {
  15. int[] cell = queue.poll();
  16. int x = cell[0], y = cell[1];
  17. for (int i = 0; i < 4; i++) {
  18. int mx = x + dx[i], my = y + dy[i];
  19. if (mx >= 0 && mx < n && my >= 0 && my < m && image[mx][my] == currColor) {
  20. queue.offer(new int[]{mx, my});
  21. image[mx][my] = newColor;//涂色
  22. }
  23. }
  24. }
  25. return image;
  26. }
  27. }

深度搜索

基于递归dfs方法实现

  1. class Solution {
  2. int[] dx = {1, 0, 0, -1};
  3. int[] dy = {0, 1, -1, 0};
  4. public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
  5. int currColor = image[sr][sc];
  6. if (currColor != newColor) {
  7. dfs(image, sr, sc, currColor, newColor);
  8. }
  9. return image;
  10. }
  11. public void dfs(int[][] image, int x, int y, int color, int newColor) {
  12. if (image[x][y] == color) {
  13. image[x][y] = newColor;
  14. for (int i = 0; i < 4; i++) {
  15. int mx = x + dx[i], my = y + dy[i];
  16. if (mx >= 0 && mx < image.length && my >= 0 && my < image[0].length) {
  17. dfs(image, mx, my, color, newColor);
  18. }
  19. }
  20. }
  21. }
  22. }