Java数组首尾路径可达性判断方法代码排查求助
Fixing Your Java Path-Finding Recursive Method
Alright, let's walk through the bugs in your code and fix it up properly—your recursive approach is on the right track, but there are a few critical mistakes throwing things off:
Key Issues in Your Original Code
- Incorrect
tempinitialization: You created an integer array withint temp = new int [i];instead of grabbing the step count from the current index. You needint temp = a[i];to get how far you can move left/right from positioni. - Wrong end condition: The last valid index of an array is
a.length - 1, nota.length. Your checkif(i==a.length)will never trigger since indices start at 0. - Overly strict left movement boundary:
i-temp>0blocks you from moving to index 0 (a valid position). It should bei-temp >= 0to allow movement to the start of the array. - Order of operations error: You were setting
a[i] = 0(to mark visited) before capturing the step value. You need to save the step count first, otherwise you'll lose the number of steps you can take from that position.
Corrected Code
public static boolean isWay(int []a){ // Handle edge cases: null, empty array, or starting with 0 (can't move) if(a == null || a.length == 0 || a[0] == 0){ return false; } // Clone the array to avoid modifying the original input int[] visitedArray = a.clone(); return isWay(visitedArray, 0); } private static boolean isWay(int[] a, int i){ // Check if we've reached the last index (the array's end) if(i == a.length - 1){ return true; } // If current position is 0, we've already visited it or can't move if(a[i] == 0){ return false; } // Capture the number of steps we can take from this position int stepCount = a[i]; // Mark current position as visited to prevent infinite loops a[i] = 0; // Check right movement first (if within bounds) boolean canMoveRight = (i + stepCount < a.length) && isWay(a, i + stepCount); if(canMoveRight){ return true; } // Check left movement (if within bounds) boolean canMoveLeft = (i - stepCount >= 0) && isWay(a, i - stepCount); if(canMoveLeft){ return true; } // Neither direction leads to the end return false; }
Quick Notes on Improvements
- Cloning the array: This ensures we don't modify the original input array, which is a best practice—callers of your method won't have their array unexpectedly changed.
- Edge case handling: Added checks for null, empty arrays, and starting with 0 to make the method more robust.
- Clear variable names: Renamed
temptostepCountfor better readability.
Testing this with your example array [2,4,1,6,4,2,4,3,5] will correctly return true, following the path you described.
内容的提问来源于stack exchange,提问作者Eden Tamam
相关产品推荐
相关产品推荐

