Advertisement
LeatherDeer

Untitled

Dec 4th, 2022
472
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.48 KB | None | 0 0
  1. public int dfs(int[][] grid, int i, int j) {
  2.         int curArea;
  3.         if (i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || grid[i][j] == 0) {
  4.             return 0;
  5.         }
  6.  
  7.         grid[i][j] = 0;
  8.         curArea = (1 + dfs(grid, i - 1, j) + dfs(grid, i + 1, j) + dfs(grid, i, j - 1) + dfs(grid, i, j + 1));
  9.         return curArea;
  10. }
  11.  
  12. class Solution {
  13.     public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
  14.         dfs(image, sr, sc, newColor, image[sr][sc]);
  15.         return image;
  16.     }
  17.    
  18.     void dfs(int[][] img, int i, int j, int col, int target) {
  19.         if (i < 0 || i >= img.length || j < 0 || j >= img[0].length || img[i][j] != target || img[i][j] == col) {
  20.             return;
  21.         }
  22.        
  23.         img[i][j] = col;
  24.         dfs(img, i + 1, j, col, target);
  25.         dfs(img, i - 1, j, col, target);
  26.         dfs(img, i, j + 1, col, target);
  27.         dfs(img, i, j - 1, col, target);
  28.     }
  29. }
  30.  
  31. class Solution {
  32.     List<String> ans = new ArrayList<>();
  33.    
  34.     public List<String> binaryTreePaths(TreeNode root) {
  35.         dfs(root, "");
  36.         return ans;
  37.     }
  38.    
  39.     void dfs(TreeNode root, String path) {
  40.         if (root == null) {
  41.             return;
  42.         }
  43.        
  44.         if (root.left == null && root.right == null) {
  45.             ans.add(path + root.val);
  46.             return;
  47.         }
  48.        
  49.         dfs(root.left, path + root.val + "->");
  50.         dfs(root.right, path + root.val + "->");
  51.     }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement