1.1【问题描述】
已知地图中的描述,是根据陆地和海水交错排布的,其中数字1表示陆地,0表示海水,被水围起来的区域称为“岛屿”。已知师徒四人处在(m,n) 点,请你按照八戒的提示编写程序计算所在岛屿的面积。 (注: 地图使用二维数组存储,地图的大小不超过50*50)1.2【输入输出说明】
输入: 四个整数m,n,x;y,其中m和n表示图的行和列,x和y表示你所处的横纵坐标
输出: 你所在岛屿的面积。(注:假设地图上的边界点之外均为海水)
1.3【样例】
输入:
6 6 3 4
0 1 0 1 1 0
0 0 0 1 1 1
1 0 1 1 0 1
0 0 0 1 0 0
0 1 1 1 1 0
0 0 0 0 0 0输出:
13
就是定位自己的坐标,然后进行完全深搜遍历即可;
void bfs(){
que[tail].x=ax;
que[tail].y=ay;
tail++;
while(tail>head){
for(int i=0;i<4;i++){
tx=que[head].x+nt[i][0];
ty=que[head].y+nt[i][1];
if(tx<1 ||tx>m ||ty<1 ||ty>n) continue;
if(map[tx][ty]==1 &&book[tx][ty]==0){
que[tail].x=tx;
que[tail].y=ty;
book[tx][ty]=1;
tail++;
ans++;
}
}
head++;
}
}
#include
using namespace std;
int m,n,ax,ay,tx,ty; //ax,ay初位置;tx,ty过渡位置
int head=1,tail=1;
int map[51][51],book[51][51];
int ans=1;
struct node{
int x,y;
}que[2501];
int nt[4][2]={{1,0},{-1,0},{0,1},{0,-1}}; //四个方向
void bfs(){
que[tail].x=ax;
que[tail].y=ay;
tail++;
while(tail>head){
for(int i=0;i<4;i++){
tx=que[head].x+nt[i][0];
ty=que[head].y+nt[i][1];
if(tx<1 ||tx>m ||ty<1 ||ty>n) continue;
if(map[tx][ty]==1 &&book[tx][ty]==0){
que[tail].x=tx;
que[tail].y=ty;
book[tx][ty]=1;
tail++;
ans++;
}
}
head++;
}
}
int main(){
cin>>m>>n>>ax>>ay;
for(int i=1;i<=m;i++){
for(int j=1;j<=n;j++){
cin>>map[i][j];
}
}
book[ax][ay]=1;
bfs();
cout<
2.1【题目描述】
地图由m行n列的0和1的数字矩阵组成其中0表示海水,1表示陆地,岛屿的定义为沿陆地的上下左右四个方向仍为陆地,则为同一块岛屿,请你编写程序计算地图上有多少个独立的岛屿。 (注: 地图使用二维数组存储,地图的大小不超过50*50)
2.2【输入输出说明】
输入: 第一行为两个整数,m和n(1
输出: 岛屿的个数
2.3【样例】
输入:
6 6
0 1 0 1 0 0
0 0 0 1 0 1
1 0 1 1 0 1
0 0 0 0 0 0
0 1 1 1 1 0
0 0 0 0 0 0输出
5
遍历地图就好了,看bfs会被调用多少次,就是几个岛屿;bfs时,在同一个岛屿就把map[i][j]=0即可。
void bfs(int ax,int ay){
//记得每次调用bfs都要重置一下
head=1,tail=1;
que[tail].x=ax;
que[tail].y=ay;
map[ax][ay]=0;
tail++;
while(tail>head){
for(int i=0;i<4;i++){
tx=que[head].x+nt[i][0];
ty=que[head].y+nt[i][1];
if(tx<1 ||tx>m ||ty<1 ||ty>n) continue;
if(map[tx][ty]){
que[tail].x=tx;
que[tail].y=ty;
map[tx][ty]=0; //既然是一个岛屿,直接看作0就行了
tail++;
}
}
head++;
}
}
#include
using namespace std;
int m,n,tx,ty; //ax,ay初位置;tx,ty过渡位置
int head=1,tail=1;
int map[51][51];
int ans=0;
struct node{
int x,y;
}que[2501];
int nt[4][2]={{1,0},{-1,0},{0,1},{0,-1}}; //四个方向
void bfs(int ax,int ay){
//记得每次调用bfs都要重置一下
head=1,tail=1;
que[tail].x=ax;
que[tail].y=ay;
map[ax][ay]=0;
tail++;
while(tail>head){
for(int i=0;i<4;i++){
tx=que[head].x+nt[i][0];
ty=que[head].y+nt[i][1];
if(tx<1 ||tx>m ||ty<1 ||ty>n) continue;
if(map[tx][ty]){
que[tail].x=tx;
que[tail].y=ty;
map[tx][ty]=0; //既然是一个岛屿,直接看作0就行了
tail++;
}
}
head++;
}
}
int main(){
cin>>m>>n;
for(int i=1;i<=m;i++){
for(int j=1;j<=n;j++){
cin>>map[i][j];
}
}
for(int i=1;i<=m;i++){
for(int j=1;j<=n;j++){
if(map[i][j]){
bfs(i,j);
ans++;
}
}
}
cout<