题目
* * 题目描述:
* * 给定一个由 ‘1’(陆地)和 ‘0’(水)组成的的二维网格,计算岛屿的数量。
* * 一个岛被水包围,并且它是通过水平方向或垂直方向上相邻的陆地连接而成的。
* * 你可以假设网格的四个边均被水包围。
* *
* * 输出描述:
* * 岛屿的数量
* *
* * 示例输入:
* *
* * 5 5
* * 1 1 1 1 0
* * 1 1 0 1 0
* * 1 1 0 0 0
* * 0 0 0 0 0
* *
* * 示例输出: 1
测试代码
/***********************************************************************
* * 题目描述:
* * 给定一个由 ‘1’(陆地)和 ‘0’(水)组成的的二维网格,计算岛屿的数量。
* * 一个岛被水包围,并且它是通过水平方向或垂直方向上相邻的陆地连接而成的。
* * 你可以假设网格的四个边均被水包围。要求可以持续的工作
* *
* * 输出描述:
* * 岛屿的数量
* *
* * 示例输入:
* *
* * 5 5
* * 1 1 1 1 0
* * 1 1 0 1 0
* * 1 1 0 0 0
* * 0 0 0 0 0
* *
* * 示例输出: 1
* ***********************************************************************/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#define DEBUG
/* 保存矩阵的行数和列数 */
int g_row = 0;
int g_col = 0;
/* 递归访问当前节点的上下左右 */
/* row 行标 */
/* col 列标 */
void DFS(int *src,int row,int col)
{
*(src+row*g_col+col) = 0; /* 遍历后置零 */
if( row-1 >= 0 && 1 == *(src+(row-1)*g_col+col) ) /* 上 */
{
DFS(src,row-1,col);
}
if(row+1<=g_row-1&& 1 == *(src + (row+1)*g_col+col)) /* 下 */
{
DFS(src,row+1,col);
}
if( col-1 >= 0 && 1 == *(src+row*g_col+col-1) ) /* 左 */
{
DFS(src,row,col-1);
}
if( col+1 <= g_col-1 && 1 == *(src+row*g_col+col+1) ) /* 右 */
{
DFS(src,row,col+1);
}
}
/* 判断岛屿数量 */
int isLand(int *src)
{
int i,j;
if(NULL == src)
{
printf("[Error]:input is NULL!\n\r");
return -1;
}
int count=0;
/* 遍历矩阵 */
for(i=0;i<g_row;i++)/* 行 */
{
for(j=0;j<g_col;j++)/* 列 */
{
if(1 == *(src+i*g_col+j)) /* 如果是陆地,则进入深度遍历 */
{
DFS(src,i,j); /* 深度优先遍历,同一片的遍历后置零 */
count++;
}
}
}
return count;
}
int main()
{
int i;
int* land_data = NULL;
scanf("%d %d",&g_row,&g_col); /* 第一行连续输入矩阵的行数和列数 */
if( 0 == g_row || 0 == g_row )
{
printf("[Error]:row or clo is zero,Can't continue!\n\r");
return -1;
}
land_data = malloc(sizeof(int)*g_row*g_col);
if(NULL == land_data)
{
printf("[Error]:Malloc Failed!\n\r");
return -1;
}
for(i=0 ; i < g_row*g_col ;i++)
{
scanf("%d",land_data + i);
}
#ifdef DEBUG
printf("[提示]:岛屿数量为:%d.\n\r",isLand(land_data));
#else
printf("%d\n",isLand(land_data));
#endif
if(NULL != land_data)
{
free(land_data);
land_data = NULL;
}
return 0;
}
测试结果

注意事项
输入数据时注意要用空格隔开,以免scanf函数不认识。
660

被折叠的 条评论
为什么被折叠?



