您的位置:首页 > 其它

200. Number of Islands

2016-04-20 00:13 399 查看
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

方法一:用并查集(写的比较长,不够简洁,用时24ms)

vector<int>f;
int find(int k)
{
if(f[k]==-1) return k;
else return f[k]=find(f[k]);
}

void fun(int a,int b)
{
int fa,fb;
fa=find(a);
fb=find(b);
if(fa!=fb) f[fa]=fb;
}

int numIslands(vector<vector<char> >& grid)
{
int n=grid.size();
if(n==0) return 0;
int m=grid[0].size();
f.resize(n*m,-1);
vector<int>point;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(grid[i][j]=='1')
{
int p=i*m+j;
point.push_back(p);
if(i>0&&grid[i-1][j]=='1') fun(p-m,p);
if(i<n-1&&grid[i+1][j]=='1') fun(p+m,p);
if(j>0&&grid[i][j-1]=='1') fun(p-1,p);
if(j<n-1&&grid[i][j+1]=='1') fun(p+1,p);
}
}
}
set<int>s;
for(int i=0;i<point.size();i++)
{
int tmp=find(point[i]);
s.insert(tmp);
}
return s.size();
}


方法2:DFS(参考讨论,用时12ms)

void eliminate(vector<vector<char> >&grid,int row,int col)
{
if(row < 0 || col < 0 || row == grid.size() || col == grid[row].size()) return ;
if(grid[row][col] == '1')
{
grid[row][col] = '0';
eliminate(grid, row - 1, col);
eliminate(grid, row + 1, col);
eliminate(grid, row, col - 1);
eliminate(grid, row, col + 1);
}
return ;
}

int numIslands(vector<vector<char> >& grid)
{
int n=grid.size();
if(n==0) return 0;
int m=grid[0].size();
int count=0;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(grid[i][j]=='1')
{
count++;
eliminate(grid,i,j);
}
}
}
return count;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  dfs 并查集