Skip to content

Commit 982b788

Browse files
committed
Added 01 Matrix in cpp
1 parent 01283f1 commit 982b788

2 files changed

Lines changed: 80 additions & 0 deletions

File tree

cpp/01 Matrix.cpp

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
/*
2+
PROBLEM STATEMENT:
3+
Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell.
4+
The distance between two adjacent cells is 1.
5+
Input: mat = [[0,0,0],[0,1,0],[0,0,0]]
6+
Output: [[0,0,0],[0,1,0],[0,0,0]]
7+
Input: mat = [[0,0,0],[0,1,0],[1,1,1]]
8+
Output: [[0,0,0],[0,1,0],[1,2,1]]
9+
Constraints:
10+
m == mat.length
11+
n == mat[i].length
12+
1 <= m, n <= 104
13+
1 <= m * n <= 104
14+
mat[i][j] is either 0 or 1.
15+
There is at least one 0 in mat.
16+
*/
17+
#include<iostream>
18+
#include<bits/stdc++.h>
19+
using namespace std;
20+
21+
/*
22+
Idea: As there can be multiple sources and multiple destinations so use BFS
23+
and also cost is unit and is not changing
24+
*/
25+
26+
//direction array
27+
vector<vector<int>> dir={{1,0},{0,1},{0,-1},{-1,0}};
28+
bool isValid(int i,int j,int m,int n){
29+
if(i==m || j==n || i<0 ||j<0) return false;
30+
return true;
31+
}
32+
void solve(vector<vector<int>> &matrix,vector<vector<int>> &ans){
33+
queue<pair<int,int>> q;
34+
int m=matrix.size(), n=matrix[0].size();
35+
for(int i=0;i<m;i++){
36+
for(int j=0;j<n;j++){
37+
//as 0 distance from itself so use them as source
38+
if(matrix[i][j]==0){
39+
q.push({i,j}); //pushing the coordinates
40+
ans[i][j]=0; //updating distance as 0
41+
}
42+
}
43+
}
44+
//BFS
45+
while(!q.empty()){
46+
pair<int,int> curr=q.front();
47+
q.pop();
48+
//iterate for 4 directions
49+
for(auto it:dir){
50+
int a=curr.first+it[0];
51+
int b=curr.second+it[1];
52+
//checking out of bound and unvisited condition
53+
if(isValid(a,b,m,n) && ans[a][b]==-1){
54+
q.push({a,b});
55+
ans[a][b]=ans[curr.first][curr.second]+1;//updating with level+1
56+
}
57+
}
58+
}
59+
60+
}
61+
62+
int main(){
63+
int m,n;
64+
cin>>m>>n;
65+
vector<vector<int>> matrix(m,vector<int>(n));
66+
for(int i=0;i<m;i++){
67+
for(int j=0;j<n;j++){
68+
cin>>matrix[i][j];
69+
}
70+
}
71+
vector<vector<int>> ans(m,vector<int>(n,-1));
72+
solve(matrix,ans);
73+
for(int i=0;i<m;i++){
74+
for(int j=0;j<n;j++){
75+
cout<<ans[i][j]<<" ";
76+
}
77+
cout<<endl;
78+
}
79+
return 0;
80+
}

cpp/a.exe

7.8 KB
Binary file not shown.

0 commit comments

Comments
 (0)