簡體   English   中英

給定一個矩陣,找出所有相鄰的相同元素

[英]Given a matrix find all adjacent same elements

我有一個二維矩陣,現在我想選擇一個元素e並查看所有相鄰元素 (i+1,j), (i-1,j) , (i,j+1), (i,j-1)並導航它們是否與e相同並計算有多少是這樣匹配的。 現在找到可能的最大計數。

例子:

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

輸出: 5。

因為4是重復5次並且都是相鄰的元素,而1只出現了2次,2只出現了3次。

如何解決這個程序? 我嘗試過 BFS,但被困在這里如何保持計數?

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);
}

您需要遍歷網格以識別每個 BFS 的起點。 此外,您需要在每個 BFS 開始時初始化一個新計數,並在每次訪問相鄰單元時增加它。 然后取每個這樣的計數的最大值。

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;
}

測試:

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));

輸出:

Max = 5

比簡單!

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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM