Topic
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 are formed by connecting adjacent lands horizontally or vertically. Assume all four edges of the grid is all surrounded by water.
Example 1:
11110
11010
11000
00000
Answer:1
Example 2:
11000
11000
00100
00011
Answer:3
Ideas
can refer to: Find the number of islands
A little different is that this topic only takes four directions, and the reference topic is considered in 8 directions.
Code
/ *------------------------------------------------------* Date: 2014-04-10* sjf0115* title: 200.Number of islands* Net Address: https://leetcode.com/problems/number-of-islands/* Result: ac* Source: leetcode* Blog:--------------------------------------------------------* *#include <iostream>#include <vector>using namespace STD;classSolution { Public:intNumislands ( vector<vector<char>>&grid) {//number of rows introw = Grid.size ();if(Row = =0){return 0; }//if //Number of columns intCol = grid[0].size ();if(col = =0){return 0; }//if intCount =0; for(inti =0; i < row;++i) { for(intj =0; J < Col;++j) {//If it is 1 and has not been visited, discover a new island if(Grid[i][j] = =' 1 '){//Take a deep traversal of the islandDFS (GRID,ROW,COL,I,J); ++count; }//if}//for}//for returnCount }Private://Grid map Row rows col number (x, y) current coordinates voidDFS ( vector<vector<char> >&grid,intRowintColintXintY) {if(X <0|| Y <0|| X >= Row | | Y >= Col | | Grid[x][y] = =' 0 '){return; }//ifGrid[x][y] =' 0 ';// RightDFS (grid,row,col,x,y+1);// LeftDFS (grid,row,col,x,y-1);//TopDFS (grid,row,col,x-1, y);//BottomDFS (grid,row,col,x+1, y); }};intMain () {solution solution; vector<vector<char> >Grid = {{' 1 ',' 1 ',' 0 ',' 0 ',' 0 '}, {' 1 ',' 1 ',' 0 ',' 0 ',' 0 '}, {' 0 ',' 0 ',' 1 ',' 0 ',' 0 '}, {' 0 ',' 0 ',' 0 ',' 1 ',' 1 '} };cout<<solution.numislands (GRID) <<endl;return 0;}
Run time
[Leetcode]200.number of Islands