1. 程式人生 > 實用技巧 >77 。01 矩陣(542)

77 。01 矩陣(542)

作者: Turbo時間限制: 1S章節: 寬度優先搜尋

晚於: 2020-08-26 12:00:00後提交分數乘係數50%

截止日期: 2020-09-02 12:00:00

問題描述 :

給定一個由 0 和 1 組成的矩陣,找出每個元素到最近的 0 的距離。

兩個相鄰元素間的距離為 1 。

示例 1:

輸入:

0 0 0

0 1 0

0 0 0

輸出:

0 0 0

0 1 0

0 0 0

示例 2:

輸入:

0 0 0

0 1 0

1 1 1

輸出:

0 0 0

0 1 0

1 2 1

注意:

給定矩陣的元素個數不超過 10000。

給定矩陣中至少有一個元素是 0。

矩陣中的元素只在四個方向上相鄰: 上、下、左、右。

可使用以下main函式:

int main()

{

vector<vector<int> > matrix;

int m,n;

cin>>m;

cin>>n;

char ch;

for(int i=0; i<m; i++)

{

vector<int> aLine;

for(int j=0; j<n; j++)

{

cin>>ch;

aLine.push_back(ch-'0');

}

matrix.push_back(aLine);

}

vector<vector<int>> res=Solution().updateMatrix(matrix);

for(int i=0; i<res.size(); i++)

{

vector<int> aLine = res[i];

for(int j=0; j<aLine.size(); j++)

cout<<aLine[j];

cout<<endl;

}

return 0;

}

輸入說明 :

首先輸入矩陣的行數m和列數n,m*n<=10000

然後輸入m行,每行n個字元0或1。中間無空格分隔。

輸出說明 :

輸出結果,0、1之間無空格。

輸入範例 :

輸出範例 :

#include <iostream>
#include <vector> 
#include <queue>
using namespace std;

class Solution {
public:
    const int dx[4]={0,0,-1,1};
    const int dy[4]={1,-1,0,0};
    vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) 
    {
        int m=matrix.size();
        int n=matrix[0].size();
        queue<pair<int,int>> q;
        vector<vector<int>> res(m,vector<int>(n,INT_MAX)) ;//相當於m*n的陣列,並初始化數值為無窮大 
        for(int i=0;i<m;i++)
        {
            for(int j=0;j<n;j++)
                if(matrix[i][j]==0)
                {
                    res[i][j]=0;//所有為0的點自身結果為0 
                    q.push({i,j});
                }
        }
        while(!q.empty())
        {
            pair<int,int> front=q.front();
            q.pop();
            for(int i=0;i<4;i++)
            {
                int newx=front.first+dx[i];
                int newy=front.second+dy[i];
                if(newx>=0&&newx<m&&newy>=0&&newy<n)
                {
                    if(res[newx][newy]>res[front.first][front.second]+1)//值大於上一個值得大小加1,則更新 
                    {
                        res[newx][newy]= res[front.first][front.second]+1;
                        q.push({newx,newy}) ;//加入佇列,為了搜尋其他的值 
                    } 
                }
            }
        }
        return res;
    }
};

int main()
{
    vector<vector<int> > matrix;
    int m,n;
    cin>>m;
    cin>>n;

    char ch;
    for(int i=0; i<m; i++)
    {
        vector<int> aLine;
        for(int j=0; j<n; j++)
        {
            cin>>ch;
            aLine.push_back(ch-'0');
        }
        matrix.push_back(aLine);
    }

    vector<vector<int>> res=Solution().updateMatrix(matrix);
    for(int i=0; i<res.size(); i++)
    {
        vector<int> aLine = res[i];
        for(int j=0; j<aLine.size(); j++)
            cout<<aLine[j];
        cout<<endl;
    }
    return 0;
}

https://leetcode-cn.com/problems/01-matrix/solution/c-bfsxiang-jie-by-yi-zhi-ri-shi-jiu/