📌  相关文章
📜  矩阵的所有连接的非空单元格的大小

📅  最后修改于: 2021-09-07 02:03:12             🧑  作者: Mango

给定一个二元矩阵mat[][] ,任务是找到所有可能的非空连接单元的大小。

例子:

方法:
这个想法是在矩阵上使用 BFS 和递归。
请按照以下步骤操作:

  • 初始化队列数据结构并插入一个单元格( mat[i][j] = 1 )。
  • 对插入的单元格执行BFS并遍历其相邻单元格。
  • 检查边界条件并检查当前元素是否为1 ,然后将其翻转为0
  • 标记访问过的单元格并更新连接的非空单元格的大小。
  • 最后,打印获得的连接的所有大小。

下面是上述方法的实现:

C++14
// C++ Program to implement
// the above approach
#include 
using namespace std;
 
// Function to find size of all the
// islands from the given matrix
int BFS(vector >& mat,
        int row, int col)
{
    int area = 0;
 
    // Initialize a queue for
    // the BFS traversal
    queue > Q;
    Q.push({ row, col });
 
    // Iterate untill the
    // queue is empty
    while (!Q.empty()) {
 
        // Top element of queue
        auto it = Q.front();
 
        // Pop the element
        Q.pop();
 
        int r = it.first, c = it.second;
 
        // Check for boundaries
        if (r < 0 || c < 0 || r > 4 || c > 4)
            continue;
 
        // Check if current element is 0
        if (mat[r] == 0)
            continue;
 
        // Check if current element is 1
        if (mat[r] == 1) {
 
            // Mark the cell visited
            mat[r] = 0;
 
            // Incrementing the size
            area++;
        }
 
        // Traverse all neighbors
        Q.push({ r + 1, c });
        Q.push({ r - 1, c });
        Q.push({ r, c + 1 });
        Q.push({ r, c - 1 });
    }
 
    // Return the answer
    return area;
}
 
// Function to print size of each connections
void sizeOfConnections(vector > mat)
{
 
    // Stores the size of each
    // connected non-empty
    vector result;
 
    for (int row = 0; row < 5; ++row) {
        for (int col = 0; col < 5; ++col) {
 
            // Check if the cell is
            // non-empty
            if (mat[row][col] == 1) {
 
                // Function call
                int area = BFS(mat, row, col);
                result.push_back(area);
            }
        }
    }
 
    // Print the answer
    for (int val : result)
        cout << val << " ";
}
 
// Driver Code
int main()
{
 
    vector > mat
        = { { 1, 1, 0, 0, 0 },
            { 1, 1, 0, 1, 1 },
            { 1, 0, 0, 1, 1 },
            { 1, 0, 0, 0, 0 },
            { 0, 0, 1, 1, 1 } };
 
    sizeOfConnections(mat);
 
    return 0;
}


Java
// Java program to implement
// the above approach
import java.util.*;
import java.lang.*;
 
class GFG{
     
static class pair
{
    int first, second;
    pair(int first, int second)
    {
        this.first = first;
        this.second = second;
    }
}
 
// Function to find size of all the
// islands from the given matrix
static int BFS(int[][] mat,
               int row, int col)
{
    int area = 0;
     
    // Initialize a queue for
    // the BFS traversal
    Queue Q = new LinkedList<>();
    Q.add(new pair(row, col));
 
    // Iterate untill the
    // queue is empty
    while (!Q.isEmpty())
    {
         
        // Top element of queue
        pair it = Q.peek();
 
        // Pop the element
        Q.poll();
 
        int r = it.first, c = it.second;
 
        // Check for boundaries
        if (r < 0 || c < 0 ||
            r > 4 || c > 4)
            continue;
 
        // Check if current element is 0
        if (mat[r] == 0)
            continue;
 
        // Check if current element is 1
        if (mat[r] == 1)
        {
             
            // Mark the cell visited
            mat[r] = 0;
 
            // Incrementing the size
            area++;
        }
 
        // Traverse all neighbors
        Q.add(new pair(r + 1, c));
        Q.add(new pair(r - 1, c));
        Q.add(new pair(r, c + 1));
        Q.add(new pair(r, c - 1));
    }
 
    // Return the answer
    return area;
}
 
// Function to print size of each connections
static void sizeOfConnections(int[][] mat)
{
     
    // Stores the size of each
    // connected non-empty
    ArrayList result = new ArrayList<>();
 
    for(int row = 0; row < 5; ++row)
    {
        for(int col = 0; col < 5; ++col)
        {
             
            // Check if the cell is
            // non-empty
            if (mat[row][col] == 1)
            {
                 
                // Function call
                int area = BFS(mat, row, col);
                result.add(area);
            }
        }
    }
     
    // Print the answer
    for(int val : result)
       System.out.print(val + " ");
}
 
// Driver code
public static void main (String[] args)
{
    int[][] mat = { { 1, 1, 0, 0, 0 },
                    { 1, 1, 0, 1, 1 },
                    { 1, 0, 0, 1, 1 },
                    { 1, 0, 0, 0, 0 },
                    { 0, 0, 1, 1, 1 } };
                     
    sizeOfConnections(mat);
}
}
 
// This code is contributed by offbeat


Python3
# Python3 program to implement
# the above approach
from collections import deque
 
# Function to find size of all the
# islands from the given matrix
def BFS(mat, row, col):
     
    area = 0
 
    # Initialize a queue for
    # the BFS traversal
    Q = deque()
    Q.append([row, col])
 
    # Iterate untill the
    # queue is empty
    while (len(Q) > 0):
         
        # Top element of queue
        it = Q.popleft()
 
        # Pop the element
        # Q.pop();
        r, c = it[0], it[1]
 
        # Check for boundaries
        if (r < 0 or c < 0 or r > 4 or c > 4):
            continue
 
        # Check if current element is 0
        if (mat[r] == 0):
            continue
 
        # Check if current element is 1
        if (mat[r] == 1):
 
            # Mark the cell visited
            mat[r] = 0
 
            # Incrementing the size
            area += 1
             
        # Traverse all neighbors
        Q.append([r + 1, c])
        Q.append([r - 1, c])
        Q.append([r, c + 1])
        Q.append([r, c - 1])
 
    # Return the answer
    return area
 
# Function to prsize of each connections
def sizeOfConnections(mat):
     
    # Stores the size of each
    # connected non-empty
    result = []
 
    for row in range(5):
        for col in range(5):
             
            # Check if the cell is
            # non-empty
            if (mat[row][col] == 1):
                 
                # Function call
                area = BFS(mat, row, col);
                result.append(area)
 
    # Print the answer
    for val in result:
        print(val, end = " ")
 
# Driver Code
if __name__ == '__main__':
 
    mat = [ [ 1, 1, 0, 0, 0 ],
            [ 1, 1, 0, 1, 1 ],
            [ 1, 0, 0, 1, 1 ],
            [ 1, 0, 0, 0, 0 ],
            [ 0, 0, 1, 1, 1 ] ]
 
    sizeOfConnections(mat)
 
# This code is contributed by mohit kumar 29


C#
// C# program to implement
// the above approach
using System;
using System.Collections;
using System.Collections.Generic;
 
class GFG{
 
class pair
{
    public int first, second;
     
    public pair(int first, int second)
    {
        this.first = first;
        this.second = second;
    }
}
 
// Function to find size of all the
// islands from the given matrix
static int BFS(int[, ] mat, int row, int col)
{
    int area = 0;
 
    // Initialize a queue for
    // the BFS traversal
    Queue Q = new Queue();
    Q.Enqueue(new pair(row, col));
 
    // Iterate untill the
    // queue is empty
    while (Q.Count != 0)
    {
         
        // Top element of queue
        pair it = Q.Peek();
 
        // Pop the element
        Q.Dequeue();
 
        int r = it.first, c = it.second;
 
        // Check for boundaries
        if (r < 0 || c < 0 || r > 4 || c > 4)
            continue;
 
        // Check if current element is 0
        if (mat[r, c] == 0)
            continue;
 
        // Check if current element is 1
        if (mat[r, c] == 1)
        {
             
            // Mark the cell visited
            mat[r, c] = 0;
             
            // Incrementing the size
            area++;
        }
 
        // Traverse all neighbors
        Q.Enqueue(new pair(r + 1, c));
        Q.Enqueue(new pair(r - 1, c));
        Q.Enqueue(new pair(r, c + 1));
        Q.Enqueue(new pair(r, c - 1));
    }
 
    // Return the answer
    return area;
}
 
// Function to print size of each connections
static void sizeOfConnections(int[,] mat)
{
     
    // Stores the size of each
    // connected non-empty
    ArrayList result = new ArrayList();
 
    for(int row = 0; row < 5; ++row)
    {
        for(int col = 0; col < 5; ++col)
        {
             
            // Check if the cell is
            // non-empty
            if (mat[row, col] == 1)
            {
                 
                // Function call
                int area = BFS(mat, row, col);
                result.Add(area);
            }
        }
    }
 
    // Print the answer
    foreach(int val in result)
        Console.Write(val + " ");
}
 
// Driver code
public static void Main(string[] args)
{
    int[, ] mat = { { 1, 1, 0, 0, 0 },
                    { 1, 1, 0, 1, 1 },
                    { 1, 0, 0, 1, 1 },
                    { 1, 0, 0, 0, 0 },
                    { 0, 0, 1, 1, 1 } };
 
    sizeOfConnections(mat);
}
}
 
// This code is contributed by grand_master


输出:
6 4 3

时间复杂度: O(row * col)
辅助空间: O(row * col)

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live