Advertisement
exmkg

Untitled

Feb 13th, 2025
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.37 KB | None | 0 0
  1. class Solution {
  2.     public boolean canReach(int[] arr, int start) {
  3.         boolean[] visited = new boolean[arr.length];
  4.         return dfs(arr, start, visited);
  5.     }
  6.  
  7.     private boolean dfs(int[] arr, int current, boolean[] visited) {
  8.         if (arr[current] == 0) {
  9.             return true;
  10.         }
  11.         visited[current] = true;
  12.         int left = current - arr[current];
  13.         int right = current + arr[current];
  14.         if (left >= 0 && !visited[left]) {
  15.             if (dfs(arr, left, visited)) {
  16.                 return true;
  17.             }    
  18.         }
  19.         if (right < arr.length && !visited[right]) {
  20.             if (dfs(arr, right, visited)) {
  21.                 return true;
  22.             }
  23.         }
  24.         return false;
  25.     }
  26. }
  27.  
  28. /*
  29.     arr = [4, 2, 3, 0, 3, 1, 2], start = 5
  30.    
  31.     dfs(..., 5, [0, 0, 0, 0, 0, 0, 0])
  32.       arr[5] -> 1
  33.       visited[5] = true
  34.       left = 4
  35.       right = 6
  36.      
  37.       dfs(..., left = 4, [0, 0, 0, 0, 0, 1, 0])
  38.         arr[4] -> 3
  39.         visited[4] = true
  40.         left = 1
  41.         right = 7
  42.  
  43.         dfs(..., left = 1, [0, 0, 0, 0, 1, 1, 0])
  44.           arr[1] -> 2
  45.           visited[1] = true
  46.           left = -1
  47.           right = 3
  48.  
  49.           dfs(..., right = 3, [0, 1, 0, 0, 1, 1, 0])
  50.             arr[3] -> 0
  51.             return true
  52.           return true
  53.         return true
  54.     return true
  55. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement