随便写写-求最大的岛面积
情景描述如下:
输入m*n的矩阵,矩阵中的0代表陆地,1代表水域,被水域包围的岛的最大面积;
如下矩阵:
1 1 0 1 1 1 1 1
0 1 0 1 0 1 0 0
1 0 0 1 0 1 0 1
1 1 1 0 0 0 1 0
1 0 0 1 0 0 0 1
1 1 1 0 1 1 1 1
1 0 0 0 0 0 0 0
1 0 1 1 1 0 1 0
最大的岛面积为8;
型如:
输入:
首先是行数m和列数n;
然后是一个m*n的矩阵;
输出:
输出最大的岛的面积;
代码如下:
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int x;
int y;
} node;
int Isempty(int rear,int head)
{ //判断队列是否为空,为空则返回真,否则返回假
if(rear==head)
return 1;
else
return 0;
}
node Dequeue(int head,node stepqueue[])
{ //出队处理,输入参数为队首以及队列数组,返回数组中节点
return stepqueue[head];
}
void Enqueue(int rear,node stepqueue[],int x,int y)
{ //入队处理,输入参数为对尾、队列数组、矩阵节点对应的横纵坐标
stepqueue[rear].x=x;
stepqueue[rear].y=y;
}
int main()
{
int data[10][10],row,col,i,j,head=0,rear=0; //存储矩阵及行列定义
node stepqueue[100];
scanf("%d%d",&row,&col);
for(i=0;i<row;i++)
for(j=0;j<col;j++)
scanf("%d",&data[i][j]);
int now,max=0,flag=0;
for(i=0;i<row;i++)
for(j=0;j<col;j++) //对整个矩阵进行遍历
if(data[i][j]!=1)
{
flag=0;
now=0;
data[i][j]=1; //将矩阵中的0置为1,避免重复访问
Enqueue(rear,stepqueue,j,i); //发现0进行入队处理
rear++; //队尾指针加一
if(i==0||j==0||i==row||j==col) //判断是否为边界节点
flag=1;
now++;
while(!Isempty(rear,head)) //以发现的第一个节点为中心进行搜索;
{
node currentstep=Dequeue(head,stepqueue);
head++; //队首指针加一
int x,y;
x=currentstep.x;
y=currentstep.y;
if((y-1)>=0&&data[y-1][x]==0) //第一步,对当前节点的正上方节点进行搜索;
{
if((y-1)==0) //判断邻接节点是否为边界节点
flag=1;
data[y-1][x]=1;
Enqueue(rear,stepqueue,x,y-1);
rear++;
now++;
}
if((x+1)<col&&data[y][x+1]==0) //第二布,对当前节点的右侧节点进行搜索;
{
if((x+1)==(col-1)) //判断邻接节点是否为边界节点
flag=1;
data[y][x+1]=1;
Enqueue(rear,stepqueue,x+1,y);
rear++;
now++;
}
if((y+1)<row&&data[y+1][x]==0)//第三步,对当前节点的正下方节点进行搜索;
{
if((y+1)==(row-1)) //判断邻接节点是否为边界节点
flag=1;
data[y+1][x]=1;
Enqueue(rear,stepqueue,x,y+1);
rear++;
now++;
}
if((x-1)>=0&&data[y][x-1]==0) //第四步,对当前节点的左侧节点进行搜索;
{
if((x-1)==0) //判断邻接节点是否为边界节点
flag=1;
data[y][x-1]=1;
Enqueue(rear,stepqueue,x-1,y);
rear++;
now++;
}
}
if(now>max&&flag==0)
max=now;
}
printf("最大的岛面积为%d",max);
}
感觉题目比较有意思,就是代码写的有点糙,欢迎高手指教;
态度决定高度,细节决定成败,

浙公网安备 33010602011771号