总结
世间起因于洪水灌溉算法竟然我没写对,在检查了好几遍之后发现竟然是二维数组的初始化为1出现了问题,memset不可以用!!于是写下总结
代码
#include<iostream>
#include<algorithm>
#include<cstring>
#include<queue>
using namespace std;
int n,m;
typedef pair<int,int> PII;
int a[1000][1000] = {1};
PII start,endd;
int dx[]={0,0,1,-1};
int dy[]={1,-1,0,0};
void sov(){
queue<PII>q;
q.push(start);
int ans = 1;
while(q.size()){
PII tp = q.front();
q.pop();
int x= tp.first;
int y = tp.second;
a[x][y] = 1;
for(int i =0 ; i < 4; i++){
int xx = x + dx[i];
int yy = y + dy[i];
if(xx < 0 || yy < 0 || xx > n || yy > m ||a[xx][yy] == 1) continue;
else{
q.push({xx,yy});
a[xx][yy] = 1;
ans++;
}
}
}
q.push(endd);
int ans2 = 1;
while(q.size()){
PII tp = q.front();
q.pop();
int x= tp.first;
int y = tp.second;
a[x][y] = 1;
for(int i =0 ; i < 4; i++){
int xx = x + dx[i];
int yy = y + dy[i];
if(xx < 0 || yy < 0 || xx > n || yy > m ||a[xx][yy] == 1) continue;
else{
q.push({xx,yy});
a[xx][yy] = 1;
ans2++;
}
}
}
if(ans < ans2) cout << ans2 <<endl;
else cout << ans << endl;
}
int main(){
int flag = 0;
cin >> n >> m;
for(int i = 0; i <= n; i++){
for(int j = 0; j <= m; j++)
a[i][j] = 1;
}
for(int i =1; i <= n; i++)
for(int j = 1; j <=m; j++ )
{
cin >> a[i][j];
if(!flag && a[i][j] == 0)
{
start.first = i;
start.second = j;
flag = 1;
}
else if (a[i][j] == 0){
endd.first = i;
endd.second = j;
}
}
sov();
}
//不能通过memset 将数组赋值除了0 或者-1 以外的任何值
//不能将a[100][100] = {1}将该数组全部赋值为1
//可以通过vector<vector<int>> a(n, vector<int>(m, 1));