| 2 | |
| 3 | class Solution { |
| 4 | public boolean canJump(int[] nums) { |
| 5 | /* |
| 6 | * Constraints |
| 7 | * 1 <= nums.length <= 10^4 |
| 8 | * 0 <= nums[i] <= 10^5 |
| 9 | * |
| 10 | * Solution |
| 11 | * 1. Use BFS Algorithm. |
| 12 | * - reason 1 : have to ignore array which is not visited. |
| 13 | * - reason 2 : we have to visit all possible array from array[start]. |
| 14 | */ |
| 15 | |
| 16 | int N = nums.length; |
| 17 | ArrayDeque<Integer> q = new ArrayDeque<>(); |
| 18 | boolean[] visited = new boolean[N]; |
| 19 | |
| 20 | // First, add first array index. |
| 21 | // And, set visited[first_index] to true. |
| 22 | q.add(0); |
| 23 | visited[0] = true; |
| 24 | |
| 25 | // Axiom : if N is 1, result is true. |
| 26 | if(N == 1) return true; |
| 27 | |
| 28 | // BFS algorithm |
| 29 | while(!q.isEmpty()) { |
| 30 | int cur = q.poll(); |
| 31 | |
| 32 | // find cur + 1 to cur + nums[cur] |
| 33 | for(int i = 1; i <= nums[cur]; i++) { |
| 34 | if(cur + i >= N - 1) return true; |
| 35 | int next = Math.min(cur + i, N - 1); |
| 36 | |
| 37 | // set visited[next] to true and add index into queue. |
| 38 | // because of time limit(No overlap steps.) |
| 39 | if(!visited[next]) { |
| 40 | visited[next] = true; |
| 41 | q.add(next); |
| 42 | } |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | return false; |
| 47 | |
| 48 | } |
| 49 | } |