【问题标题】:How to check if 2 elements are adjacent to one another in 2D array如何检查二维数组中的2个元素是否彼此相邻
【发布时间】:2026-02-14 03:55:01
【问题描述】:

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

示例 1:

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

示例 2:

在这种情况下,如果起始整数 = 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
                }

            }
        }
     }
}

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

我将如何检查这个?

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

【问题讨论】:

  • 链接您查看过的其他帖子可能会有所帮助。另外,在考虑代码之前,您是否制定了解决问题的策略?在您的示例中,元素的顺序为 0-8,是否任何整数都可以位于任何位置,例如{{8, 1, 3}, {2, 7, 6}, {5, 0, 4}} 或 `{{54, 873, 932} ... }?您所说的“始终保持不变”是指在初始化之后吗?我首先会考虑如何判断元素是否彼此相邻,然后考虑如何处理(字面)边缘情况。

标签: java multidimensional-array


【解决方案1】:

如果您的 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;
}

【讨论】:

    【解决方案2】:

    如果已知矩阵的内容仅包含维度rows x cols 内的范围[min..max) 中的数字,则最好检查startdestination 是否都属于此范围以及它们必须不同(自相邻被忽略)。

    使用start 值可以计算rowcol 值。

    最后检查目的地是否在相邻的单元格中。

    注意:如果startdestination 相邻,则该方法应返回布尔值true,否则返回false

    // default matrix 3x3, starting from 0
    public static boolean check(int start, int destination) {
        return check(start, destination, 3);
    }
    
    // square matrix n x n, starting from 0
    public static boolean check(int start, int destination, int n) {
        return check(start, destination, 0, n, n);
    }
    
    // rectangular matrix rows x cols, starting from 0
    public static boolean check(int start, int destination, int rows, int cols) {
        return check(start, destination, 0, rows, cols);
    }
    
    // rectangular matrix rows x cols, starting from min
    public static boolean check(int start, int destination, int min, int rows, int cols) {
        int max = min + rows * cols - 1;
        if (start < min || start > max || destination < min || destination > max || start == destination) {
            return false;
        }
        int rs = (start - min) / cols;
        int cs = (start - min) % cols;
    
        int rd = (destination - min) / cols;
        int cd = (destination - min) % cols;
        
        return ((rs == rd + 1 || rd == rs + 1) && (cs == cd))
            || ((cs == cd + 1 || cd == cs + 1) && (rs == rd));
    }    
    

    测试(打印矩阵和邻接图):

    public static void matrix(int min, int rows, int cols) {
        System.out.print(" | ");
        for (int i = 0; i < cols; i++) {
            System.out.printf("%2d  ", i);
        }
        System.out.println("\n" + "=".repeat(1 + cols * 4));
    
        int max = min + rows * cols;
        for (int i = 0; i < rows; i++) {
            System.out.print(i + "| ");
            for (int j = 0; j < cols; j++) {
                System.out.printf("%2d  ", min + cols * i + j);
            }
            System.out.println();
        }
    }
    
    public static void adjacency(int min, int rows, int cols) {
        int max = min + rows * cols;
        System.out.printf("Range: [ %2d, %2d)%n", min, max);
        System.out.print("  | ");
        for (int i = min; i < max; i++) {
            System.out.printf("%2d  ", i);
        }
        System.out.println("\n" + "=".repeat(4 + rows * cols * 4));
        for (int i = min; i < max; i++) {
            System.out.printf("%2d| ", i);
            for (int j = min; j < max; j++) {
                System.out.printf("%2s  ", check(i, j, min, rows, cols) ? "Y": ".");
            }
            System.out.println();
        }
    }
    

    测试:

    int min = -4, rows = 3, cols = 4;
    matrix(min, rows, cols);
    adjacency(min, rows, cols);
    

    输出:

     |  0   1   2   3  
    =================
    0| -4  -3  -2  -1  
    1|  0   1   2   3  
    2|  4   5   6   7  
    Range: [ -4,  8)
      | -4  -3  -2  -1   0   1   2   3   4   5   6   7  
    ====================================================
    -4|  .   Y   .   .   Y   .   .   .   .   .   .   .  
    -3|  Y   .   Y   .   .   Y   .   .   .   .   .   .  
    -2|  .   Y   .   Y   .   .   Y   .   .   .   .   .  
    -1|  .   .   Y   .   .   .   .   Y   .   .   .   .  
     0|  Y   .   .   .   .   Y   .   .   Y   .   .   .  
     1|  .   Y   .   .   Y   .   Y   .   .   Y   .   .  
     2|  .   .   Y   .   .   Y   .   Y   .   .   Y   .  
     3|  .   .   .   Y   .   .   Y   .   .   .   .   Y  
     4|  .   .   .   .   Y   .   .   .   .   Y   .   .  
     5|  .   .   .   .   .   Y   .   .   Y   .   Y   .  
     6|  .   .   .   .   .   .   Y   .   .   Y   .   Y  
     7|  .   .   .   .   .   .   .   Y   .   .   Y   .  
    

    对于 min = 0,rows = 3,cols = 3:

    Range: [  0,  9)
      |  0   1   2   3   4   5   6   7   8  
    ========================================
     0|  .   Y   .   Y   .   .   .   .   .  
     1|  Y   .   Y   .   Y   .   .   .   .  
     2|  .   Y   .   .   .   Y   .   .   .  
     3|  Y   .   .   .   Y   .   Y   .   .  
     4|  .   Y   .   Y   .   Y   .   Y   .  
     5|  .   .   Y   .   Y   .   .   .   Y  
     6|  .   .   .   Y   .   .   .   Y   .  
     7|  .   .   .   .   Y   .   Y   .   Y  
     8|  .   .   .   .   .   Y   .   Y   .  
    

    【讨论】:

    • 这是否可以用于任何网格大小?
    • 当然,你是对的,这个解决方案可以很容易地为各种范围参数化[min, max),其中max = min + rows * cols;,然后一行/一列计算为rs = (start - min) / cols; cs = (start - min) % cols等。在给定的例如min = 0; rows = cols = 3;.
    【解决方案3】:

    这是一个可能提供想法的示例。但是你仍然需要做一些编码。

    public class Main
    {
        private static final int MAX_COLUMNS = 3; //matrix[0].length
    
        public static void main(String[] args)
        {
            final int[][] matrix = {
                { 1, 2, 3 },
                { 4, 5, 6 },
                { 7, 8, 9 },
            };
    
            for(int i=1; i <= 9; ++i) {
                final int start = i;
                //final int target = 7;
    
                final int row = getRow(start - 1);
                final int column = getColumn(start - 1);
    
                final int left = getLeft(matrix, row, column);
                final int top = getTop(matrix, row, column);
                final int right = getRight(matrix, row, column);
                final int bottom = getBottom(matrix, row, column);
    
                System.out.printf("[%d] L: %2d, T: %2d, R: %2d, B: %2d%n", start, left, top, right, bottom);
    
                //[1] L: -1, T: -1, R:  2, B:  4
                //[2] L:  1, T: -1, R:  3, B:  5
                //[3] L:  2, T: -1, R: -1, B:  6
                //[4] L: -1, T:  1, R:  5, B:  7
                //[5] L:  4, T:  2, R:  6, B:  8
                //[6] L:  5, T:  3, R: -1, B:  9
                //[7] L: -1, T:  4, R:  8, B: -1
                //[8] L:  7, T:  5, R:  9, B: -1
                //[9] L:  8, T:  6, R: -1, B: -1
            }
        }
    
        private static final int getColumn(final int index)
        {
            return (index % MAX_COLUMNS);
        }
    
        private static final int getRow(final int index)
        {
            return (index / MAX_COLUMNS);
        }
        
        private static final int getLeft(final int[][] matrix, final int row, final int column)
        {
            if(column == 0) return -1;
            return matrix[row][column - 1];
        }
        
        private static final int getTop(final int[][] matrix, final int row, final int column)
        {
            if(row == 0) return -1;
            return matrix[row - 1][column];
        }
        
        private static final int getRight(final int[][] matrix, final int row, final int column)
        {
            if(column == (MAX_COLUMNS - 1)) return -1;
            return matrix[row][column + 1];
        }
        
        private static final int getBottom(final int[][] matrix, final int row, final int column)
        {
            if(row == (matrix.length - 1)) return -1;
            return matrix[row + 1][column];
        }
    
      // Unused in this example. In case someone need it.
        private static final int getIndex(final int row, final int column)
        {
            return row * MAX_COLUMNS + column;
        }
    
    }
    

    【讨论】: