Number of Islands

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

class Solution {
public:
    void visit(vector<vector<char> > &grid, int m, int n, vector<vector<bool> > &flag, int i, int j)
    {
	    if (i-1 >= 0 && !flag[i-1][j] && grid[i-1][j] == '1')
	    {
		    flag[i-1][j] = true;
		    visit(grid, m, n, flag, i-1, j);
	    }
	
	    if (i+1 < m && !flag[i+1][j] && grid[i+1][j] == '1')
	    {
		    flag[i+1][j] = true;
		    visit(grid, m, n, flag, i+1, j);
	    }
	
	    if (j-1 >= 0 && !flag[i][j-1] && grid[i][j-1] == '1')
	    {
		    flag[i][j-1] = true;
		    visit(grid, m, n, flag, i, j-1);
	    }
	
	    if (j+1 < n && !flag[i][j+1] && grid[i][j+1] == '1')
	    {
		    flag[i][j+1] = true;
		    visit(grid, m, n, flag, i, j+1);
	    }
    }
    
    int numIslands(vector<vector<char>>& grid) {
        int result = 0;
	    int m = grid.size();
	    if (m < 1)
	    {
		    return 0;
	    }
	    int n = grid[0].size();
	    if (n < 1)
	    {
		    return 0;
	    }

	    vector<bool> temp(n, false);
	    vector<vector<bool> > flag(m, temp);
	    for (int i = 0; i < m; i++)
	    {
		    for (int j = 0; j < n; j++)
		    {
			    if (!flag[i][j] && grid[i][j] == '1')
			    {
				    result++;
				    visit(grid, m, n, flag, i, j);
			    }
		    }
	    }

	    return result;
    }
};


你可能感兴趣的:(Number of Islands)