首页 > 解决方案 > 如何检查二维数组中的2个元素是否彼此相邻

问题描述

我试图弄清楚如何接受 2 个整数参数,一个称为“start”的初始整数和一个称为“destination”的第二个整数。我想使用我的方法中的两个参数,首先检查起始整数是否在矩阵内,然后检查目标整数是否在它周围的 4 个元素内相邻 - (北、东、南、西)。

示例 1:

示例1

如果起始整数是(6),则检查目标整数(7)是否与起始整数相邻。如果是真的,那就做点什么。

示例 2:

示例1

在这种情况下,如果起始整数 = 4 且目标整数 = 2。程序不会认为这些元素是相邻的。

初始化数组:

int[][] matrix = {{0,1,2,}, 
                  {3,4,5,}, 
                  {6,7,8}};

检查方法:

public static  double check(int start, int destination)
{

    for(int row = 0; row < matrix.length; row++)
    {
        for(int col = 0; col < matrix[0].length; col++)
        {
            // check if the start integer is in the matrix
            if(matrix[row][col] == start)
            {
                // check if destination integer is adjacent to starting integer:
                if (destination is adjacent to start)
                {
                   // do something
                }

            }
        }
     }
}

请记住,矩阵不会有重复的数字,并且将始终保持不变。

我将如何检查这个?

我花了几个小时查看类似的 StackOverflow 帖子,但我似乎真的无法掌握给出的示例。有人可以指导我完成吗?

标签: javamultidimensional-array

解决方案


如果您的start元素在矩阵中,则有 4 个可能的位置可以检查您的destination元素:LEFT, RIGHT, UP, DOWN. 您可以添加一个默认设置为 false 的变量并检查 4 个点,记住不要越界:

public static double check(int start, int destination) {
    for (int row = 0; row < matrix.length; row++) {
        for (int col = 0; col < matrix[0].length; col++) {
            // check if the start integer is in the matrix
            if (matrix[row][col] == start) {
                // check if destination integer is adjacent to starting integer:
                boolean destIsAdj = false;
                //left
                if (col - 1 > 0 && matrix[row][col-1] == destination) 
                    destIsAdj = true;
                //right
                else if (col + 1 < matrix[0].length && matrix[row][col+1] == destination) 
                    destIsAdj = true;
                //up
                else if (row - 1 > 0 && matrix[row-1][col] == destination) 
                    destIsAdj = true;
                //down
                else if (row + 1 < matrix.length && matrix[row+1][col] == destination) 
                    destIsAdj = true;

                if (destIsAdj){
                    // adjacent! do something
                }
                else {
                    // not adjacent! do something else
                }
            }
        }
    }
    return 0.0;
}

推荐阅读