Hi All,
I've got a C# solution to https://leetcode.com/problems/number-of-islands/ but I'm having trouble submitting it because of something that seems to be a bug in leetcode (perhaps). The code to my solution is at the end of this post.
There are two documented ways to get the size of each dimension of an array in C#: ary.GetUpperBound(dimension) + 1 or ary.GetLength(dimension). I've tried both, but I get an exception (also below).
The interesting bit is that some wrapper seems to be pointing the GetUpperBound call to GetLowerBound somehow? Anyways, the solution requires knowledge of the size of each dimension.
Anybody else run into this?
Thanks in advance for any insights / thoughts!
-Brian
System.IndexOutOfRangeException: Index was outside the bounds of the array.
at (wrapper managed-to-native) System.Array.GetLowerBound(System.Array,int)
Line 0: System.Array.GetUpperBound (System.Int32 dimension) in <a1ae6166591d4020b810288d19af38d4>
Line 4: Solution.NumIslands (System.Char[][] grid) in Solution.cs
Line 18: DriverSolution.Helper (System.Char[][] param_1) in Driver.cs
Line 33: Driver.Main (System.String[] args) in Driver.cs
[ERROR] FATAL UNHANDLED EXCEPTION: System.IndexOutOfRangeException: Index was outside the bounds of the array.
at (wrapper managed-to-native) System.Array.GetLowerBound(System.Array,int)
Line 0: System.Array.GetUpperBound (System.Int32 dimension) in <a1ae6166591d4020b810288d19af38d4>
Line 4: Solution.NumIslands (System.Char[][] grid) in Solution.cs
Line 18: DriverSolution.Helper (System.Char[][] param_1) in Driver.cs
Line 33: Driver.Main (System.String[] args) in Driver.cs
public class Solution {
public int NumIslands(char[][] grid) {
// comments below show the things I tried - for a known test case with rows 4 and cols 5 it works, but using the
// api to get rows and cols throws an exception straight away when getting the number of columns.
int rows = grid.GetUpperBound(0) + 1; // 4;// grid.GetLength(0);
int cols = grid.GetUpperBound(1) + 1; // 5;// grid.GetLength(1);
int numberOfIslands = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (grid[i][j] == '1') {
visitIsland(grid, rows, cols, i, j);
++numberOfIslands;
}
}
}
return numberOfIslands;
}
public void visitIsland(char[][] grid, int rows, int cols, int i, int j) {
if (grid[i][j] != '1') {
return;
}
grid[i][j] = '2';
// i-1, j
// i+1, j
// i, j-1
// i, j+1
if (i > 0) {
visitIsland(grid, rows, cols, i - 1, j);
}
if (i < rows - 1) {
visitIsland(grid, rows, cols, i + 1, j);
}
if (j > 0) {
visitIsland(grid, rows, cols, i, j - 1);
}
if (j < cols - 1) {
visitIsland(grid, rows, cols, i, j + 1);
}
}
}