📌  相关文章
📜  通过用 0 替换 K 的邻居来最小化使所有 Matrix 元素为 0 的步骤计数

📅  最后修改于: 2022-05-13 01:56:12.058000             🧑  作者: Mango

通过用 0 替换 K 的邻居来最小化使所有 Matrix 元素为 0 的步骤计数

给定一个大小为M*N的二维数组matrix[][]和一个整数K。对于matrix[][]中每次出现的K ,替换K及其左侧右侧的所有非零相邻元素,顶部底部0 。程序必须重复这个过程,直到矩阵中的所有值都变为零。任务是找到将给定数组matrix[][]转换为0所需的最小步骤数。如果不可能,则打印-1。

例子:

方法:想法是在左右四个方向上遍历矩阵,并在找到值为K的单元格时,使用深度优先搜索将所有相邻元素的值更改为0。按照以下步骤操作解决这个问题:

  • 将变量interations_count初始化为0
  • 使用变量row遍历范围[0, M)并执行以下任务:
    • 使用变量col遍历范围[0, N)并执行以下任务:
      • 如果matrix[row][col]等于K,则使用递归执行 DFS 以将所有可能元素的值更改为0 。还将iterations_count的值增加1。
  • 执行上述步骤后,检查任何单元格的值是否非零。如果是,则打印-1,否则打印iterations_count的值作为答案。

下面是上述方法的实现

C++
// C++ code for the above approach
#include 
using namespace std;
 
// Function to implement DFS
void traverse(int M, int N, vector >& matrix,
              int row, int col)
{
 
    // Check the boundary conditions
    if (row >= 0 && row < M && col >= 0 && col < N) {
        if (matrix[row][col] == 0) {
            return;
        }
 
        // Change that non-zero
        // adjacent element to zero
        matrix[row][col] = 0;
 
        // Traverse the matrix in left
        traverse(M, N, matrix, row, col - 1);
 
        // Traverse the matrix in Right
        traverse(M, N, matrix, row, col + 1);
 
        // Traverse the matrix in Top
        traverse(M, N, matrix, row - 1, col);
 
        //// Traverse the matrix in Bottom
        traverse(M, N, matrix, row + 1, col);
    }
}
 
void findCount(int M, int N, vector >& matrix,
               int K)
{
 
    int iterations_count = 0;
 
    // Traverse the matrix and find any element
    // equals K, if any elements is found
    // increment the interations_count variable
    // and pass the element to the traverse function
    for (int row = 0; row < M; row++) {
        for (int col = 0; col < N; col++) {
            if (K == matrix[row][col]) {
                iterations_count++;
                traverse(M, N, matrix, row, col);
            }
        }
    }
 
    for (int i = 0; i < M; i++) {
        for (int j = 0; j < N; j++) {
            if (matrix[i][j] != 0) {
                iterations_count = -1;
            }
        }
    }
 
    // Print the iterations count
    cout << iterations_count;
}
 
int main()
{
 
    // Initialize the values of M and N
    int M = 5, N = 5;
 
    // Assigning the elements of 5*5 matrix
    vector > matrix = { { 5, 6, 0, 5, 6 },
                                    { 1, 8, 8, 0, 2 },
                                    { 5, 5, 5, 0, 6 },
                                    { 4, 5, 5, 5, 0 },
                                    { 8, 8, 8, 8, 8 } };
 
    // Assign K as 6
    int K = 6;
 
    findCount(M, N, matrix, K);
    return 0;
}
 
// This code is contributed by Potta Lokesh


Java
// Java program for the above approach
public class GFG {
 
// Function to implement DFS
static void traverse(int M, int N,int matrix[][],int row, int col)
{
 
    // Check the boundary conditions
    if (row >= 0 && row < M
        && col >= 0 && col < N) {
        if (matrix[row][col] == 0) {
            return;
        }
 
        // Change that non-zero
        // adjacent element to zero
        matrix[row][col] = 0;
 
        // Traverse the matrix in left
        traverse(M, N, matrix, row, col - 1);
 
        // Traverse the matrix in Right
        traverse(M, N, matrix, row, col + 1);
 
        // Traverse the matrix in Top
        traverse(M, N, matrix, row - 1, col);
 
        //// Traverse the matrix in Bottom
        traverse(M, N, matrix, row + 1, col);
    }
}
 
static void findCount(int M, int N, int matrix[][],int K)
{
 
    int iterations_count = 0;
 
    // Traverse the matrix and find any element
    // equals K, if any elements is found
    // increment the interations_count variable
    // and pass the element to the traverse function
    for (int row = 0; row < M; row++) {
        for (int col = 0; col < N; col++) {
            if (K == matrix[row][col]) {
                iterations_count++;
                traverse(M, N, matrix, row, col);
            }
        }
    }
 
    for (int i = 0; i < M; i++) {
        for (int j = 0; j < N; j++) {
            if (matrix[i][j] != 0) {
                iterations_count = -1;
            }
        }
    }
 
    // Print the iterations count
    System.out.print(iterations_count);
}
 
// Driver Code
public static void main(String []args)
{
 
    // Initialize the values of M and N
    int M = 5, N = 5;
 
    // Assigning the elements of 5*5 matrix
    int matrix[][] = {
            { 5, 6, 0, 5, 6 },
            { 1, 8, 8, 0, 2 },
            { 5, 5, 5, 0, 6 },
            { 4, 5, 5, 5, 0 },
            { 8, 8, 8, 8, 8 } };
 
    // Assign K as 6
    int K = 6;
 
    findCount(M, N, matrix, K);
 
}
 
}
 
// This code is contributed by AnkThon


Python3
# python program for the above approach
 
# Function to implement DFS
def traverse(M,  N, matrix, row, col):
 
    # Check the boundary conditions
    if (row >= 0 and row < M and col >= 0 and col < N):
        if (matrix[row][col] == 0):
            return
 
        # Change that non-zero
        # adjacent element to zero
        matrix[row][col] = 0
 
        # Traverse the matrix in left
        traverse(M, N, matrix, row, col - 1)
 
        # Traverse the matrix in Right
        traverse(M, N, matrix, row, col + 1)
 
        # Traverse the matrix in Top
        traverse(M, N, matrix, row - 1, col)
 
        # Traverse the matrix in Bottom
        traverse(M, N, matrix, row + 1, col)
 
 
def findCount(M, N, matrix, K):
    iterations_count = 0
 
    # Traverse the matrix and find any element
    # equals K, if any elements is found
    # increment the interations_count variable
    # and pass the element to the traverse function
    for row in range(0, M):
        for col in range(0, N):
            if (K == matrix[row][col]):
                iterations_count += 1
                traverse(M, N, matrix, row, col)
 
    for i in range(0, M):
        for j in range(0, N):
            if (matrix[i][j] != 0):
                iterations_count = -1
 
    # Print the iterations count
    print(iterations_count)
 
# Driver Code
if __name__ == "__main__":
 
    # Initialize the values of M and N
    M = 5
    N = 5
 
    # Assigning the elements of 5*5 matrix
    matrix = [[5, 6, 0, 5, 6],
              [1, 8, 8, 0, 2],
              [5, 5, 5, 0, 6],
              [4, 5, 5, 5, 0],
              [8, 8, 8, 8, 8]]
 
    # Assign K as 6
    K = 6
    findCount(M, N, matrix, K)
 
    # This code is contributed by rakeshsahni


C#
// C# program for the above approach
using System;
 
public class GFG {
 
    // Function to implement DFS
    static void traverse(int M, int N,int [,]matrix,int row, int col)
    {
     
        // Check the boundary conditions
        if (row >= 0 && row < M
            && col >= 0 && col < N) {
            if (matrix[row, col] == 0) {
                return;
            }
     
            // Change that non-zero
            // adjacent element to zero
            matrix[row, col] = 0;
     
            // Traverse the matrix in left
            traverse(M, N, matrix, row, col - 1);
     
            // Traverse the matrix in Right
            traverse(M, N, matrix, row, col + 1);
     
            // Traverse the matrix in Top
            traverse(M, N, matrix, row - 1, col);
     
            //// Traverse the matrix in Bottom
            traverse(M, N, matrix, row + 1, col);
        }
    }
     
    static void findCount(int M, int N, int [,]matrix,int K)
    {
     
        int iterations_count = 0;
     
        // Traverse the matrix and find any element
        // equals K, if any elements is found
        // increment the interations_count variable
        // and pass the element to the traverse function
        for (int row = 0; row < M; row++) {
            for (int col = 0; col < N; col++) {
                if (K == matrix[row, col]) {
                    iterations_count++;
                    traverse(M, N, matrix, row, col);
                }
            }
        }
     
        for (int i = 0; i < M; i++) {
            for (int j = 0; j < N; j++) {
                if (matrix[i,j] != 0) {
                    iterations_count = -1;
                }
            }
        }
     
        // Print the iterations count
        Console.WriteLine(iterations_count);
    }
 
// Driver Code
public static void Main(String []args)
{
 
    // Initialize the values of M and N
    int M = 5, N = 5;
 
    // Assigning the elements of 5*5 matrix
    int [,]matrix = {
            { 5, 6, 0, 5, 6 },
            { 1, 8, 8, 0, 2 },
            { 5, 5, 5, 0, 6 },
            { 4, 5, 5, 5, 0 },
            { 8, 8, 8, 8, 8 } };
 
    // Assign K as 6
    int K = 6;
 
    findCount(M, N, matrix, K);
 
}
 
}
 
// This code is contributed by AnkThon


Javascript


输出
2

时间复杂度: O(M*N)
辅助空间: O(1)