<p>Given an <code>m x n</code> binary matrix <code>mat</code>, return <em>the distance of the nearest </em><code>0</code><em> for each cell</em>.</p>

<p>The distance between two adjacent cells is <code>1</code>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/04/24/01-1-grid.jpg" style="width: 253px; height: 253px;" />
<pre>
<strong>Input:</strong> mat = [[0,0,0],[0,1,0],[0,0,0]]
<strong>Output:</strong> [[0,0,0],[0,1,0],[0,0,0]]
</pre>

<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/04/24/01-2-grid.jpg" style="width: 253px; height: 253px;" />
<pre>
<strong>Input:</strong> mat = [[0,0,0],[0,1,0],[1,1,1]]
<strong>Output:</strong> [[0,0,0],[0,1,0],[1,2,1]]
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>m == mat.length</code></li>
	<li><code>n == mat[i].length</code></li>
	<li><code>1 &lt;= m, n &lt;= 10<sup>4</sup></code></li>
	<li><code>1 &lt;= m * n &lt;= 10<sup>4</sup></code></li>
	<li><code>mat[i][j]</code> is either <code>0</code> or <code>1</code>.</li>
	<li>There is at least one <code>0</code> in <code>mat</code>.</li>
</ul>

class Solution {
public:
    vector<vector<int>>visited;
    int rows,cols;
    vector<vector<int>>newM;
    vector<pair<int,int>>dir={{-1,0},{1,0},{0,-1},{0,1}};
    
    vector<vector<int>> updateMatrix(vector<vector<int>>& mat) {
        rows=mat.size();
        cols=mat[0].size();
        newM=mat;
        visited.resize(rows,vector<int>(cols,0));

        queue<pair<pair<int,int>,int>>q1;//{{row,col},distance}
        for(int i=0;i<rows;i++){
            for(int j=0;j<cols;j++){
                if(mat[i][j]==0){
                    q1.push({{i,j},0});
                    visited[i][j]=1;
                }
            }
        }

        while(!q1.empty()){
            int r=q1.front().first.first;
            int c=q1.front().first.second;
            int dist=q1.front().second;
            q1.pop();

            for(auto[r1,c1]:dir){
                int newR=r+r1;
                int newC=c+c1;

                int ans=0;
                if(newR<rows && newR>=0 && newC<cols && newC>=0 && !visited[newR][newC] && mat[newR][newC]==1){
                     visited[newR][newC]=1;
                     newM[newR][newC]=dist+1;
                     q1.push({{newR,newC},dist+1});
                }
            }
        }
        return newM;
    }
};
40649