In the last if statement you have mixed nY and nX. It could be an explanation. Also checks on the border creates double counting. There’s always eight neighbours counted, but if the cell is on the border border cells get counted twice. When nY is -1 you change it to 0 and when it is zero it’s counted again.