📌  相关文章
📜  设置二进制矩阵的所有元素所需的最少操作数

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

给定一个由 1 和 0维度组成的二进制矩阵 mat[][] M * N ,任务是找到将所有 0 转换为 1 的操作次数。在每次操作中,所有的 1 都可以将它们相邻的 0 转换为 1。

注意:对角线元素不被视为矩阵中数字的相邻元素。
例子:

方法:

  1. 遍历整个矩阵并将值为1的矩阵元素的坐标推入队列。
  2. 将队列的大小保存在变量x 中
  3. 遍历队列进行x次迭代。
  4. 对于每次迭代,都会遇到值为 1 的元素的位置。将其相邻位置的值转换为 1(仅当相邻元素为 0 时),然后将新转换的 1 的坐标推送到队列中。
  5. x次迭代中的每一次中,只要执行步骤 4,就将队列的前元素出列。
  6. 一旦遍历队列的 x 个元素,将操作数的计数增加到 1。
  7. 重复步骤 2 到步骤 6,直到队列为空。
  8. 返回队列为空后的操作次数计数。如果矩阵全为 1,则不执行任何操作,计数将为 0。

下面是上述方法的实现。

C++
// C++ code for the above approach.
  
#include 
using namespace std;
  
// function to check whether the
// adjacent neighbour is a valid
// index or not
bool check(int row, int col, 
           int r, int c) {
  
    return (r >= 0 && r < row 
            && c >= 0 && c < col);
}
  
// function to calculate the
// number of operations
int bfs(int row, int col, 
        int *grid) {
  
    // direction matrix to find
    // adjacent neighbours
    int dir[4][2] = { { 1, 0 }, 
                      { -1, 0 }, 
                      { 0, 1 }, 
                      { 0, -1 } };
  
    // queue with pair to store
    // the indices of elements
    queue > q;
  
    // scanning the matrix to push
    // initial 1 elements
    for (int i = 0; i < row; i++)
    {
        for (int j = 0; 
             j < col; j++) {
              
          if (*((grid+i*col) + j))
            q.push(make_pair(i, j));
        }
    }
  
    // Step 2 to Step 6
    int op = -1;
    while (!q.empty()) {
  
      int x = q.size();
      for (int k = 0; 
           k < x; k++) {
              
        pair p =
                 q.front();
        q.pop();
  
        // adding the values of
        // direction matrix to the 
        // current element to get
        // 4 possible adjacent
        // neighbours
        for (int i = 0;
             i < 4; i++) {
                  
          int r = p.first +
                  dir[i][0];
          int c = p.second +
                  dir[i][1];
  
          // checking the validity
          // of the neighbour
          if (*((grid+r*col) + c) == 0 
             && check(row, col, r, c)) {
                
            // pushing it to the queue
            // and converting it to 1
            q.push(make_pair(r, c));
            *((grid+r*col) + c) = 1;
          }
        }
      }
      // increasing the operation by 1
      // after the first pass
      op++;
    }
    return op;
}
  
// Driver code
int main()
{
  int row = 4, col = 5;
  int grid[][col] = 
          { { 0, 1, 1, 0, 1 },
            { 0, 1, 0, 1, 0 },
            { 0, 0, 0, 0, 1 },
            { 0, 0, 1, 0, 0 } };
      
  cout << bfs(row, col, 
              (int *)grid);
}


输出:
2


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

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