public class number_of_islands {
public static void main(String[] args) {
number_of_islands tester = new number_of_islands();
char[][] testData = {{'1', '1', '1', '1', '0'},
{'1', '1', '0', '1', '0'},
{'1', '1', '0', '0', '0'},
{'0', '0', '0', '0', '0'}};
System.out.println(tester.numIslands(testData));
}
public int numIslands (char[][] grid) {
if (grid == null || grid.length == 0) {
throw new IllegalArgumentException("Invalid argument");
}
int res = 0;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; i < grid[i].length; j++) {
if ((grid[i][j] == '0')
/* the line below is where the above error occurs */
||((i > 0) && (grid[i - 1][j] == '1'))
|| ((j > 0) && (grid[i][j - 1] == '1'))) {
continue;
}
res++;
}
}
return res;
}
}
In the code above, the numIslands function accepts an 2-d array as the input and compute something, but there is an array out of bounds error in the line below the comment, I have checked to let i > 0 and j > 0, why the question still there?
Thanks!
Just make these small changes in for loops
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
...
Your condition in the second for loop was "i < grid[i].length"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.