📜  二进制矩阵中最近的 1

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

二进制矩阵中最近的 1

给定一个 m*n 阶的二进制矩阵,任务是为矩阵中的每个 0 找到最接近 1 的距离并打印最终的距离矩阵。从任何单元格 (i,j),我们只能向上、向下、向左和向右四个方向移动。
注意:从一个单元格到另一个单元格的距离总是增加 1。
例子:

Input : m = 3, n = 4
        mat[m][n] = {{0, 0, 0, 1},
                     {0, 0, 1, 1},
                     {0, 1, 1, 0}}
Output: 3 2 1 0
        2 1 0 0
        1 0 0 1

这个问题的一个简单解决方案是对矩阵中的每个 0 递归地检查矩阵中最接近的 1。
这个问题的一个有效解决方案是使用 BFS。这是解决这个问题的算法:

  • 取距离矩阵 dist[m][n] 并用 INT_MAX 对其进行初始化。
  • 现在遍历具有值'1'的单元格(i,j)的索引的矩阵和make_pair(i,j)并将这对推入队列并更新dist [i] [j] = 0,因为与自身的距离为'1'将始终为 0。
  • 现在从队列中一个一个地弹出元素,直到它变空并在其上调用BFS
  • 在这里,我们需要找到最近的距离,我们为具有“1”的单元格调用BFS ,所以每当我们从队列中取出相邻的弹出元素时,我们尝试通过放置条件 if (dist[i][ j]+1) < 距离 [ADCi][ADCj]。然后我们更新距离矩阵中相邻元素的距离,并将这个相邻元素推入队列,完成BFS遍历并填充完整的距离矩阵。
  • 完成BFS遍历后,距离矩阵的每个单元格将包含最近的“1”的距离。

C++
// C++ program to find the minimum distance from a
// "1" in binary matrix.
#include
using namespace std;
const int MAX = 1000;
 
// distance matrix which stores the distance of
// nearest '1'
int dist[MAX][MAX];
 
// Function to find the nearest '1'
void nearestOne(int mat[][MAX], int m, int n)
{
    // two array when respective values of newx and
    // newy are added to (i,j) it gives up, down,
    // left or right adjacent of (i,j) cell
    int newx[] = {-1, 0, 1, 0};
    int newy[] = {0, -1, 0, 1};
 
    // queue of pairs to store nodes for bfs
    queue< pair > q;
 
    // traverse matrix and make pair of indices of
    // cell (i,j) having value '1' and push them
    // in queue
    for (int i=0; i poped;
    while (!q.empty())
    {
        poped = q.front();
        q.pop();
 
        // coordinate of currently popped node
        int x = poped.first;
        int y = poped.second;
 
        // now check for all adjacent of popped element
        for (int i=0; i<4; i++)
        {
            int adjx = x + newx[i];
            int adjy = y + newy[i];
 
            // if new coordinates are within boundary and
            // we can minimize the distance of adjacent
            // then update the distance of adjacent in
            // distance matrix and push this adjacent
            // element in queue for further bfs
            if (adjx>=0 && adjx=0 && adjy dist[x][y] + 1)
            {
                // update distance
                dist[adjx][adjy] = dist[x][y] + 1;
                q.push(make_pair(adjx,adjy));
            }
        }
    }
}
 
// Driver program to run the case
int main()
{
    int m = 3, n = 4;
    int mat[][MAX] = {{0, 0, 0, 1},
        {0, 0, 1, 1},
        {0, 1, 1, 0}
    };
  
    // Fills values in dist[][]
    nearestOne(mat, m, n);
 
    // print distance matrix
    for (int i=0; i


Python3
# Python3 program to find the minimum distance from a
# "1" in binary matrix.
MAX = 1000
INT_MAX = (2**32)
 
# distance matrix which stores the distance of
# nearest '1'
dist = [[0 for i in range(MAX)] for j in range(MAX)]
 
# Function to find the nearest '1'
def nearestOne(mat, m, n):
     
    # two array when respective values of newx and
    # newy are added to (i,j) it gives up, down,
    # left or right adjacent of (i,j) cell
    newx = [-1, 0, 1, 0]
    newy = [0, -1, 0, 1]
     
    # queue of pairs to store nodes for bfs
    q = []
     
    # traverse matrix and make pair of indices of
    # cell (i,j) having value '1' and push them
    # in queue
    for i in range(m):
        for j in range(n):
            dist[i][j] = INT_MAX
            if (mat[i][j] == 1):
                 
                # distance of '1' from itself is always 0
                dist[i][j] = 0
                 
                # make pair and push it in queue
                q.append([i, j])
     
    # now do bfs traversal
    # pop element from queue one by one until it gets empty
    # pair element to hold the currently popped element
    poped = []
    while (len(q)):
        poped = q[0]
        q.pop(0)
         
        # coordinate of currently popped node
        x = poped[0]
        y = poped[1]
         
        # now check for all adjacent of popped element
        for i in range(4):
             
            adjx = x + newx[i]
            adjy = y + newy[i]
             
            # if new coordinates are within boundary and
            # we can minimize the distance of adjacent
            # then update the distance of adjacent in
            # distance matrix and push this adjacent
            # element in queue for further bfs
            if (adjx >= 0 and adjx < m and adjy >= 0 and
                adjy < n and dist[adjx][adjy] > dist[x][y] + 1):
                 
                # update distance
                dist[adjx][adjy] = dist[x][y] + 1
                q.append([adjx, adjy])
 
# Driver code
m = 3
n = 4
mat= [[0, 0, 0, 1], [0, 0, 1, 1], [0, 1, 1, 0]]
 
# Fills values in dist[][]
nearestOne(mat, m, n)
 
# print distance matrix
for i in range(m):
    for j in range(n):
        print(dist[i][j], end=" ")
    print()
 
# This code is contributed by shubhamsingh10


输出:

3 2 1 0
2 1 0 0
1 0 0 1