我做了这个程序,应该淹没矩阵,但出了点问题。这是代码:
queue<Point> Qu;
int n,m;
cin>>n>>m;
int mat[n][m];
for(int i=0;i<n;++i)
for(int j=0;j<m;++j)
cin>>mat[i][j];
Point N,W,S,E,bgn;
bgn.x=0;
bgn.y=0;
Qu.push(bgn);
while(!Qu.empty()){
N.x=Qu.front().x-1; N.y=Qu.front().y;
S.x=Qu.front().x+1; S.y=Qu.front().y;
E.x=Qu.front().x; E.y=Qu.front().y+1;
W.x=Qu.front().x; W.y=Qu.front().y-1;
if(mat[N.x][N.y]==0){mat[N.x][N.y]=2;Qu.push(N);}
if(mat[S.x][S.y]==0){mat[S.x][S.y]=2;Qu.push(S);}
if(mat[E.x][E.y]==0){mat[E.x][E.y]=2;Qu.push(E);}
if(mat[W.x][W.y]==0){mat[W.x][W.y]=2;Qu.push(W);}
Qu.pop();
}
for(int i=0;i<n;++i){
for(int j=0;j<m;++j)
cout<<mat[i][j]<<" ";
cout<<endl;
}
Point 是我之前在代码中定义的结构,它仅包含 x 和 y 作为整数。如果矩阵为空,程序会正确填充矩阵,例如:如果我输入
3 3 0 0 0 0 0 0 0 0 0
我得到输出:
2 2 2 2 2 2 2 2 2
但如果我输入:
3 3 0 0 1 0 1 0 0 0 1
我明白了
2 2 1 2 1 2 2 2 1
代替
2 2 1 2 1 0 2 2 1
如果我在每次弹出后检查坐标,我会注意到它超出了边界(例如,它返回坐标 1 -1,它不应该这样做)。