如何计算矩阵中连接值的数量?

时间:2018-03-26 23:20:27

标签: performance search matrix depth-first-search breadth-first-search

给定一个2D整数数组,如何找到最大连通值组的大小?在此上下文中连接仅向上/向下/向左/向右计数,没有对角线。例如,以下数组已连接四个 3:

8 3 3 3
1 2 3 8
1 2 5 6
6 2 3 9

我不想使用强力方法对矩阵中的每个元素进行填充搜索。

此外,我如何解决相同的问题:找到矩阵中最大簇的大小。群集必须包含两个值(不多也不少)。例如,在同一矩阵中,最大的群集将是3和2,并且群集的大小为 8

8 3 3 3
1 2 3 8
1 2 5 6
6 2 3 9

1 个答案:

答案 0 :(得分:0)

您可以使用递归邻居方法来检索每个组中的邻居数量:

public class TestNeighbors{

    private static int[][] nodes = new int[][] {
                                      {8, 3, 3, 3},
                                      {1, 2, 3, 8},
                                      {1, 2, 5, 6},
                                      {6, 2, 3, 9}
                                    };
    private static int rows = nodes.length, cols = nodes[0].length;
    private static boolean[][] visited = new boolean[rows][cols];
    private static int[][] dirs = {{-1,0},{1,0},{0,-1},{0,1}};  //directions

    public static void main(String [] args){

        for(int row =0; row < rows; row++) {
            for (int col =0; col < cols; col++){
                int n = neighbors(row, col);
                if(n>0) {
                    System.out.println(row + "-"+ col+" has " +n 
                    + " neighbors of the same value ("+nodes[row][col]+")");
                }
            }
        }
    }

    private static int neighbors(int row, int col) {
        return neighbors(row, col,0);
    }

    private static int neighbors(int row, int col, int numberOfNeighbors ) {

        if(! withinBounds(row, col)) { return 0;}
        visited[row][col] = true;

        //find neighbors by iterating directions
        for( int[] dir : dirs) {
            int neighborRow = row + dir[0]; //neighbor row 
            int neighborCol = col + dir[1];//neighbor col 
            //chaeck if valid row col
            if(! withinBounds(neighborRow, neighborCol)) { continue;}
            //check for the same value 
            if(nodes[row][col] != nodes[neighborRow][neighborCol]) { continue;}
            //check if it has not been accounted for
            if(visited[neighborRow][neighborCol]) { continue;}

            numberOfNeighbors++;
            numberOfNeighbors =
                    neighbors(neighborRow, neighborCol, numberOfNeighbors);
        }

        return numberOfNeighbors;
    }

    //check address is within grid bounds
    private static boolean withinBounds(int row, int col) {
        if ((row < 0) || (row >= rows) || (col< 0) || (col >= cols)) {
            return false;
        }
        return true;
    }
}

输出:

  

0-1有3个相同值的邻居(3)
1-0有1个邻居   相同的值(1)
1-1有2个相同值的邻居(2)