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
DFS method.
#include <string> #include <vector> #include <iostream> using namespace std; /* 11110 11010 11000 00000 ->Island = 1 11000 11000 00100 00011 ->Island = 3 */ void flipBoard(vector< vector<char> >& grid, int i, int j, vector< vector<bool> >& used) { grid[i][j] = '0'; vector< vector<int> > dir { {0, 1}, {0, -1}, {-1, 0}, {1, 0}}; for(int k = 0; k < 4; ++k) { int tx = dir[k][0] + i; int ty = dir[k][1] + j; if(tx >= 0 && tx < grid.size() && ty >= 0 && ty < grid[i].size() && grid[tx][ty] == '1' && !used[tx][ty]) { used[tx][ty] = true; flipBoard(grid, tx, ty, used); } } } int numIslands(vector< vector<char> >& grid) { if(grid.size() == 0 || grid[0].size() == 0) return 0; int m = grid.size(); int n = grid[0].size(); vector< vector<bool> > used(m, vector<bool>(n, false)); int number = 0; for(int i = 0; i < m; ++i) { for(int j = 0; j < n; ++j) { if(grid[i][j] == '1' && !used[i][j]) { used[i][j] = true; flipBoard(grid, i, j, used); number++; } } } return number; } int main(void) { vector< vector<char> > matrix { {'1', '1', '0', '0', '0'}, {'1', '1', '1', '0', '0'}, {'0', '0', '1', '0', '0'}, {'0', '0', '0', '1', '1'}}; int num = numIslands(matrix); cout << num << endl; }