Olá quero solicitar ajuda para o entendimento no conceito de visitação de vizinhos em matrix. Tenho o exemplo do código abaixo mas estou com dificuldade de entender. Se houver outra sugestão de algoritmos considerando simplicidade e performance agradeço.
public class MatrizNavegacao {
static final int[] dx = {-1, 1, 0, 0}; // cima, baixo, esquerda, direita
static final int[] dy = {0, 0, -1, 1};
public static void main(String[] args) {
int[][] matriz = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int x = 1, y = 1; // célula central (5)
for (int i = 0; i < 4; i++) {
int newX = x + dx[i];
int newY = y + dy[i];
if (newX >= 0 && newX < matriz.length && newY >= 0 && newY < matriz[0].length) {
System.out.println("Vizinho: " + matriz[newX][newY]);
}
}
}
}