简体   繁体   中英

Given a matrix find all adjacent same elements

I have a 2D matrix, now I want to pick an element e and see all adjacent elements (i+1,j), (i-1,j) , (i,j+1), (i,j-1) and navigate if they are same as e and count how many are matching like that. Now find the maximum count that is possible.

example:

1 2 3 4
1 2 4 4
4 2 4 5
6 9 4 7

Output: 5.

as 4 is the element that repeats 5 times and all are adjacents, whereas 1 appears only 2 times and 2 appears only 3 times.

How to solve this program? I tried with BFS but got stuck on how to maintain the count here?

static class pair {
    int first, second;

    public pair(int first, int second) {
        this.first = first;
        this.second = second;
    }
}

static int ROW = 4;
static int COL = 4;

// Direction vectors
static int dRow[] = { -1, 0, 1, 0 };
static int dCol[] = { 0, 1, 0, -1 };

// Function to check if a cell
// is be visited or not
static boolean isValid(boolean vis[][], int row, int col) {

    // If cell lies out of bounds
    if (row < 0 || col < 0 || row >= ROW || col >= COL)
        return false;

    // If cell is already visited
    if (vis[row][col])
        return false;

    // Otherwise
    return true;
}


 static void BFS(int grid[][], boolean vis[][], int row, int col) {
    // Stores indices of the matrix cells
    Queue<pair> q = new LinkedList<>();

    // Mark the starting cell as visited
    // and push it into the queue
    q.add(new pair(row, col));
    vis[row][col] = true;

    // Iterate while the queue
    // is not empty
    int max = 0;
    while (!q.isEmpty()) {
        pair cell = q.peek();
        int x = cell.first;
        int y = cell.second;

        int v = grid[x][y];
        System.out.print(grid[x][y] + " ");

        // Go to the adjacent cells
        for (int i = 0; i < 4; i++) {
            int adjx = x + dRow[i];
            int adjy = y + dCol[i];

            if (isValid(vis, adjx, adjy)) {
                if (grid[adjx][adjx] == v) {
                    q.add(new pair(adjx, adjy));
                    vis[adjx][adjy] = true;
                }

            }
        }
    }

public static void main(String[] args) {

    // Given input matrix
    int grid[][] = { .... };
    ROW = grid.length;
    COL = grid[0].length;
    // Declare the visited array
    boolean[][] vis = new boolean[ROW][COL];

    BFS(grid, vis, 0, 0);
}

You need to iterate over the grid to identify the starting point of each BFS. Also, you need to initialize a new count at the start of each BFS and increment it each time you visit a neighboring cell. Then take the max of each such count.

static int max(int[][] grid)
{
    int rows = grid.length;
    int cols = grid[0].length;
    
    Queue<Pos> q = new LinkedList<>();
    boolean[][] visited = new boolean[rows][cols];
    
    int max = 0;
    for(int r=0; r<rows; r++)
    {
        for(int c=0; c<cols; c++)
        {
            if(!visited[r][c])
            {
                q.add(new Pos(r, c));
                visited[r][c] = true;

                int count = 0;
                while(!q.isEmpty())
                {
                    Pos p = q.poll();
                    count += 1;

                    for(int d=0; d<4; d++)
                    {
                        int i = p.r + dRow[d];
                        int j = p.c + dCol[d];
                        
                        if(i >= 0 && i < rows && j >= 0 && j < cols && !visited[i][j] && grid[i][j] == grid[r][c]) 
                        {
                            q.add(new Pos(i, j));
                            visited[i][j] = true;
                        }
                    }
                }
                max = Math.max(max, count);
            }
        }
    }
    return max;
}

Test:

int[][] grid = {{1,2,3,4},
                {1,2,4,4},
                {4,2,4,5},
                {6,9,4,7}};

System.out.printf("Max = %d%n", max(grid));

Output:

Max = 5

Bi Simple!

public static int findMaxAdjacentCount(int[][] grid) {
    boolean[][] visited = createVisitGrid(grid);
    int res = 0;

    for (int row = 0; row < grid.length; row++)
        for (int col = 0; col < grid[row].length; col++)
            if (!visited[row][col])
                res = Math.max(res, dfs(grid, visited, grid[row][col], row, col));

    return res;
}

private static int dfs(int[][] grid, boolean[][] visited, int expected, int row, int col) {
    if (row < 0 || row >= grid.length)
        return 0;
    if (col < 0 || col >= grid[row].length)
        return 0;
    if (visited[row][col] || grid[row][col] != expected)
        return 0;

    visited[row][col] = true;

    int depth = 1;
    depth += dfs(grid, visited, expected, row, col - 1);
    depth += dfs(grid, visited, expected, row, col + 1);
    depth += dfs(grid, visited, expected, row - 1, col);
    depth += dfs(grid, visited, expected, row + 1, col);
    return depth;
}

private static boolean[][] createVisitGrid(int[][] grid) {
    boolean[][] visit = new boolean[grid.length][];

    for (int row = 0; row < grid.length; row++)
        visit[row] = new boolean[grid[row].length];

    return visit;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM