Instead of writing separate if-statements for each direction, use direction arrays. Store the row and column offsets:
dr := [-1, -1, -1, 0, 0, 1, 1, 1]
dc := [-1, 0, 1, -1, 1, -1, 0, 1]
These represent all directions: up-left, up, up-right, left, right, down-left, down, down-right. Loop through them:
for i from 0 to 7:
nr := r + dr[i]
nc := c + dc[i]
if (nr, nc) is valid:
process neighbor
For -directional movement, use dr = [-1, 0, 1, 0] and dc = [0, 1, 0, -1]. This pattern keeps your code clean and reduces bugs.