返回题解分享
讨论 / 题解分享/ 帖子详情

岛屿个数(编程题) - 题解

没找到错误原因

#include <bits/stdc++.h>
#define endl '\n'
#define ll long long
using namespace std;
const int N = 50+5;
const int M = 50+5;
bool waihai = false;
int m,n;
int g[M][N];
bool landvit[M][N];
bool seavit[M][N]; 
int res;
//方向
int ldx[4]={0,0,1,-1};
int ldy[4]={1,-1,0,0};
int sdx[8]={-1,-1,-1,0,0,1,1,1};
int sdy[8]={-1,0,1,1,-1,1,-1,0}; 

//跟海洋bfs很像 
void landbfs(int x, int y){
	landvit[x][y] = true;
	queue<pair<int,int>> q;
	q.push(make_pair(x,y));
	while(!q.empty()){
		pair<int, int> cur = q.front(); q.pop();
		int xx = cur.first; int yy = cur.second;
		for(int i =0;i<4;i++){
			int nx = xx + ldx[i]; int ny = yy + ldy[i];
			if(nx<1||nx>m||ny<1||ny>n)continue;
			//同一个岛上没访问过的陆地 
			if(g[nx][ny]==1&&landvit[nx][ny]==false){
				landvit[nx][ny] = true;
				q.push(make_pair(nx,ny));
			}
		}
	}
	
} 



//遍历海洋,遇到陆地调用陆地bfs 遇到海洋打标记 
void seabfs(int x, int y){
	//初始化起始点
	seavit[x][y] = true;
	queue<pair<int,int>> q;
	q.push(make_pair(x,y));
	while(!q.empty()){
		pair<int, int> cur = q.front(); q.pop();
		int xx = cur.first; int yy = cur.second;
		//将这个点的邻域加入队列 
		for(int i = 0; i<8;i++){
			int nx = xx + sdx[i]; int ny = yy + sdy[i];
			if(nx<1||nx>m||ny<1||ny>n)continue;
						
			if(g[nx][ny]==1&&landvit[nx][ny]==false){
				//是没访问过的陆地,找到了一个新岛
				res++;
				//遍历岛的所有陆地,打标记免得重复计算 
				landbfs(nx,ny);
			}
			if(g[nx][ny]==0&&seavit[nx][ny]==false){
				//是没访问过的海洋,入队 
				seavit[nx][ny] = true;
				q.push(make_pair(nx,ny)); 
			}
			
		}
		
	}
	
	
}



void solve(){
	//多轮数据 清空前面的
	memset(landvit,false,sizeof(landvit));
	memset(seavit,false,sizeof(seavit));
	res = 0;
	//初始化图
	cin >>m >> n;
	//输入的数字之间无空格 得先string读进来切分 
	for(int i =1;i<=m;i++){
		string s;
		cin >> s;
		for(int j =1;j<=n;j++){
			g[i][j] = s[j] - '0';
		}
	}
	//最外圈找外海点作为seabfs起点
	for(int i=1;i<=m;i++){
		for(int j =1;j<=n;j++){
			if(i==1||i==m||j==1||j==n){
				//外圈点
				//没访问过的海 
				if(seavit[i][j]==false&&g[i][j]==0){
					waihai = true;
					seabfs(i,j);
				}	
			}
		}
	} 
	
	if(waihai == false){
		res = 1;
	}
	
	cout << res << endl;
	
}

int main(){
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	int t;
	cin >> t;
//	t = 1;
	while(t--){
		solve();
	} 
	return 0;
}
0 回复 0 转发 0 喜欢 5 阅读
回复 (0)
默认 最新
暂无回复,快来抢沙发!