简体   繁体   English

C ++中充满洪水的困难

[英]Difficulties with flood fill in c++

I made this program that should flood fill the matrix but something went wrong. 我制作了该程序,该程序应将矩阵充满,但是出了点问题。 Here's the code: 这是代码:

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 is a struct I defined earlier in code and it contains only x and y as integers. Point是我之前在代码中定义的结构,它仅包含x和y作为整数。 The program fills the matrix correctly if it's empty eg : If i enter 如果程序为空,则程序正确填充矩阵,例如:如果我输入

3 3
0 0 0
0 0 0
0 0 0

I get the output : 我得到的输出:

2 2 2
2 2 2
2 2 2

But if i enter: 但是如果我输入:

3 3
0 0 1
0 1 0
0 0 1

I get 我懂了

2 2 1
2 1 2
2 2 1

instead of 代替

2 2 1
2 1 0
2 2 1

If I check the coordinates after every pop, I can notice that it goes out of boundaries ( eg it returns the coordinates 1 -1 and it shouldn't do it). 如果我在每次弹出后检查坐标,我会注意到它超出了边界(例如,它返回坐标1 -1,因此不应该这样做)。

You set the coords of N,W,S and E, even if they are invalid; 您可以设置N,W,S和E的坐标,即使它们无效也是如此; for example if you start at (0,0) and do this: 例如,如果您从(0,0)开始并执行以下操作:

N.x=Qu.front().x-1; 
N.y=Qu.front().y;
...
if(mat[N.x][N.y]==0) {
    mat[N.x][N.y]=2;
    Qu.push(N);
} 

N will be (-1,0). N将为(-1,0)。 Instead you only check a direction if you are not at the border of the matrix. 相反,如果您不在矩阵的边界,则仅检查方向。 For example for N you could do: 例如,对于N您可以执行以下操作:

if(Qu.front().x > 0) {
    N.x=Qu.front().x-1; 
    N.y=Qu.front().y;
    if(mat[N.x][N.y]==0) {
        mat[N.x][N.y]=2;
        Qu.push(N);
    } 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM