给出大小为N x M的二进制矩阵。任务是为每个像元查找矩阵中最接近1的距离。距离计算为| i1 – i2 | + | j1 – j2 |,其中i1,j1是当前单元格的行号和列号,而i2,j2是值1的最近单元格的行号和列号。]
输入:输入的第一行是一个整数T,它表示测试用例的数量。然后是T测试用例。每个测试用例包含2行。每个测试用例的第一行包含两个整数M和N,它们表示矩阵的行数和列数。然后在下一行是矩阵(mat)的N * M个空格分隔的值。
输出:对于换行中的每个测试用例,请在一行中用空格隔开打印所需的距离矩阵。
Constraints: 1 <= T <= 20 1 <= N, M <= 500 Example: Input: 2 2 2 1 0 0 1 1 2 1 1 Output: 0 1 1 0 0 0
说明:
Testcase 1: 1 0 0 1 0 at {0, 1} and 0 at {1, 0} are at 1 distance from 1s at {0, 0} and {1, 1} respectively.
代码:
bool isSafe(int currRow,int currCol,int n,int m){
return currRow>=0 && currRow<n && currCol>=0 && currCol<m;
}
int bfs(int currX,int currY,vector<int> matrix[],int n,int m) {
queue<pair<int,int>> q;
q.push(make_pair(currX,currY));
static int rows[]={0,-1,0,1};
static int columns[]={1,0,-1,0};
int flag=0;
int dist=0;
while(flag==0 && !q.empty()) {
pair<int,int> p=q.front();
q.pop();
for(int i=0;i<4;i++) {
if(isSafe(p.first+rows[i],p.second+columns[i],n,m)) {
if(matrix[p.first+rows[i]][p.second+columns[i]]) {
dist=abs(p.first+rows[i]-currX)+abs(p.second+columns[i]-currY);
flag=1;
break;
} else {
q.push(make_pair(p.first+rows[i],p.second+columns[i]));
}
}
}
}
return dist;
}
void minDist(vector<int> matrix[],int n,int m) {
int dist[n][m];
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
if(matrix[i][j]) {
dist[i][j]=0;
} else {
dist[i][j]=bfs(i,j,matrix,n,m);
}
}
}
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
cout<<dist[i][j]<<" ";
}
}
}
Agorithm:
1. If matrix[i][j] == 1
dist[i][j]=0
else
dist[i][j]= bfs with source as (i,j)
给出大小为N x M的二进制矩阵。任务是为每个像元查找矩阵中最接近1的距离。距离计算为| i1 – i2 | + | j1 – j2 |,其中i1,j1是行号,...
您的算法效率不高,因为每次“仅”运行BFS都会更新一个单元。