static int[] dx = {1, -1, 0, 0, 1, 1, -1, -1}; static int[] dy = {0, 0, 1, -1, 1, -1, 1, -1}; ... for (int j = 0; j < 8; j++) { int nx = p.x + dx[j]; int ny = p.y + dy[j]; if(nx < 0 || ny < 0 || nx >= N || ny >= N) continue; //arr[nx][ny] }