题目链接

图像渲染

题目描述

image.png
image.png

实现代码

基于栈采用BFS广度优先遍历方式实现代码如下(结果超时):

  1. class Solution {
  2. public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
  3. int m = image.length;
  4. int n = image[0].length;
  5. Stack<Integer> stackX = new Stack<>();
  6. Stack<Integer> stackY = new Stack<>();
  7. stackX.add(sr);
  8. stackY.add(sc);
  9. int oldColor = image[sr][sc];
  10. image[sr][sc] = newColor;
  11. while (!stackX.isEmpty()) {
  12. int x = stackX.pop();
  13. int y = stackY.pop();
  14. if(x+1 < m && image[x+1][y] == oldColor) {
  15. stackX.add(x+1);
  16. stackY.add(y);
  17. image[x+1][y] = newColor;
  18. }
  19. if(x-1 >= 0 && image[x-1][y] == oldColor) {
  20. stackX.add(x-1);
  21. stackY.add(y);
  22. image[x-1][y] = newColor;
  23. }
  24. if(y+1 < n && image[x][y+1] == oldColor) {
  25. stackX.add(x);
  26. stackY.add(y+1);
  27. image[x][y+1] = newColor;
  28. }
  29. if(y-1 >= 0 && image[x][y-1] == oldColor) {
  30. stackX.add(x);
  31. stackY.add(y-1);
  32. image[x][y-1] = newColor;
  33. }
  34. }
  35. return image;
  36. }
  37. }

基于队列采用BFS广度优先遍历实现代码如下(结果居然没超时,离谱):

  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. while (!queue.isEmpty()) {
  14. int[] cell = queue.poll();
  15. int x = cell[0], y = cell[1];
  16. for (int i = 0; i < 4; i++) {
  17. int mx = x + dx[i], my = y + dy[i];
  18. if (mx >= 0 && mx < n && my >= 0 && my < m && image[mx][my] == currColor) {
  19. queue.offer(new int[]{mx, my});
  20. image[mx][my] = newColor;
  21. }
  22. }
  23. }
  24. return image;
  25. }
  26. }

采用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. }