找出由‘1’组成的孤岛
面试题目,来自leetcode,曾经败在了这个简单的小题。。
Given a 2d grid map of '1'
s (land) and '0'
s (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example 1:
11110 11010 11000 00000
Answer: 1
Example 2:
11000 11000 00100 00011
Answer: 3
、、、、、、、、、、、、My accepted Answer、、、、、、、、、、、、、、
遍历整个数组,如果发现‘1’就将其及其临接的‘1’修改为0,就是这样。
int numIslands(char** grid, int gridRowSize, int gridColSize) {
int Islands_Num = 0;
for(int rowIdx = 0; rowIdx < gridRowSize; rowIdx++)
{
for(int columIdx = 0; columIdx < gridColSize; columIdx++)
{
if('1' == grid[rowIdx][columIdx])
{
ConverToZero(grid,rowIdx, columIdx, gridRowSize, gridColSize);
Islands_Num++;
}
}
}
return Islands_Num;
}
void ConverToZero(char** grid, int rowIdx, int columIdx, int gridRowSize, int gridColSize)
{
if( (rowIdx >= gridRowSize)||(columIdx >= gridColSize) ||(rowIdx < 0)||(columIdx < 0) )
return;
if('1' == grid[rowIdx][columIdx])
{
grid[rowIdx][columIdx] = '0';
}
else
return;
ConverToZero(grid,rowIdx+1,columIdx, gridRowSize,gridColSize );
ConverToZero(grid,rowIdx-1,columIdx, gridRowSize,gridColSize );
ConverToZero(grid,rowIdx,columIdx+1, gridRowSize,gridColSize );
ConverToZero(grid,rowIdx,columIdx-1, gridRowSize,gridColSize );
}
一直感觉面试考算法题,没有毛意义!