题解 | #岛屿数量#
岛屿数量
http://www.nowcoder.com/practice/0c9664d1554e466aa107d899418e814e
class Solution { public: /** * 判断岛屿数量 * @param grid char字符型vector<vector<>> * @return int整型 */ int solve(vector<vector<char> >& grid) { // write code here if(grid.empty()||grid[0].empty()){ return 0; } vector<vector<bool>> visted(grid.size(),vector<bool>(grid[0].size(),false)); int count = 0; for(int i = 0; i < grid.size(); i++){ for(int j = 0; j < grid[i].size(); j++){ if(grid[i][j]=='1'&&!visted[i][j]){ count++; dfs(grid, i, j, visted); } } } return count; } void dfs(vector<vector<char> >& grid, int r, int c, vector<vector<bool>>& visted){ if(r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] == '0' || visted[r][c]){ return; } visted[r][c] = true; dfs(grid, r+1, c, visted); dfs(grid, r-1, c, visted); dfs(grid, r, c+1, visted); dfs(grid, r, c-1, visted); } };