Not sure what I've done wrong...

You shouldn't be making an (N+2) x (N+2) array to work on NxN elements let alone (N+1)x(N+1).
You should be writing exceptions for edge squares, using if-elseif-else statements.