Your code has:
for (int i = 0; i < rowcol.GetLength(0); i++)
{
for (int j = 0; j < rowcol[i].GetLength(0); j++)
{
int iadd = i + 1;
int iminus = i - 1;
int jadd = i + 1;
int jminus = i - 1;
And then you're trying to access the arrays with
var self = rowcol[i][j];
var top = rowcol[iminus][j];
var bottom = rowcol[iadd][j];
var left = rowcol[i][jminus];
var right = rowcol[i][jadd];
This will on all the edge cases because iminus
will be one -1
, and iadd
will rowcol.Length
, and the same for jminus
/ jadd
. These indexes are outside the bounds of your arrays. You can fix this by simply discarding the edge cases in your loop:
for (int i = 1; i < rowcol.Length - 1; i++)
{
for (int j = 1; j < rowcol[i].Length - 1; j++)
{
int iadd = i + 1;
int iminus = i - 1;
int jadd = i + 1;
int jminus = i - 1;
This will ensure that you are not accessing any elements outside the array's boundaries. But this alone will not be enough to ensure the exception never occurs. Look again at these lines:
var top = rowcol[iminus][j];
var bottom = rowcol[iadd][j];
This this will fail if the length of rowcol[iminus]
or rowcol[iadd]
is less than rowcol[i]
. So you will need to take special care to avoid this as well. Perhaps something like this:
for (int i = 1; i < rowcol.Length - 1; i++)
{
for (int j = 1; j < rowcol[i].Length - 1; j++)
{
int iadd = i + 1;
int iminus = i - 1;
int jadd = i + 1;
int jminus = i - 1;
if (j < rowcol[iminus].Length || j < rowcol[iadd].Length)
{
continue;
}
Another way you could try this would be something like this:
for (int i = 0; i < rowcol.Length; i++)
{
for (int j = 0; j < rowcol[i].Length; j++)
{
int iadd = i + 1;
int iminus = i - 1;
int jadd = i + 1;
int jminus = i - 1;
var self = rowcol[i][j];
var top = iminus >= 0 && j < rowcol[iminus].Length ? rowcol[iminus][j] : string.Empty;
var bottom = iadd < rowcol.Length && j < rowcol[iadd].Length ? rowcol[iadd][j] : string.Empty;
var left = jminus >= 0 ? rowcol[i][jminus] : string.Empty;
var right = jminus < rowcol[i].Length ? rowcol[i][jadd] : string.Empty;