import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        // Ler o número de linhas e colunas da matriz
        int M = sc.nextInt();
        int N = sc.nextInt();
        int[][] matriz = new int[M][N];

        // Ler os valores da matriz
        for (int i = 0; i < M; i++) {
            for (int j = 0; j < N; j++) {
                matriz[i][j] = sc.nextInt();
            }
        }

        // Ler o valor X a ser procurado
        int X = sc.nextInt();

        // Procurar por cada ocorrência de X na matriz e mostrar os valores adjacentes
        for (int i = 0; i < M; i++) {
            for (int j = 0; j < N; j++) {
                if (matriz[i][j] == X) {
                    System.out.println("Position " + i + "," + j + ":");
                    if (j > 0) {
                        System.out.println("Left: " + matriz[i][j - 1]);
                    }
                    if (i > 0) {
                        System.out.println("Up: " + matriz[i - 1][j]);
                    }
                    if (j < N - 1) {
                        System.out.println("Right: " + matriz[i][j + 1]);
                    }
                    if (i < M - 1) {
                        System.out.println("Down: " + matriz[i + 1][j]);
                    }
                }
            }
        }

        sc.close();
    }
}

Embed on website

To embed this program on your website, copy the following code and paste it into your website's HTML: