[LeetCode] 200. Number of Islands, leetcode200.number
Question
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
Ideas
Refer to: Find the number of islands
The difference is that this question only takes four directions into consideration, and the reference question takes eight directions into consideration.
Code
/* ---------------------------------------------------- * Date: 2014-04-10 * Author: SJF0115 * Subject: 200. number of Islands * URL: https://leetcode.com/problems/number-of-islands/* result: AC * Source: LeetCode * blog: Author */# include <iostream >#include <vector> using namespace std; class Solution {public: int numIslands (vector <char> & grid) {// number of rows int row = grid. size (); if (row = 0) {return 0;} // if // Number of columns int col = grid [0]. size (); if (col = 0) {return 0 ;}// if int count = 0; for (int I = 0; I <row; ++ I) {for (int j = 0; j <col; ++ j) {// if it is 1 and has not been accessed, a new island if (grid [I] [j] = '1') is found ') {// perform in-depth traversal of DFS (grid, row, col, I, j) using this island; ++ count ;} // if} // for return count;} private: // grid map row column (x, y) current coordinate void DFS (vector <char> & grid, int row, int col, int x, int y) {if (x <0 | y <0 | x> = row | y> = col | grid [x] [y] = '0 ') {return;} // if grid [x] [y] = '0'; // right DFS (grid, row, col, x, y + 1 ); // left DFS (grid, row, col, x, Y-1); // top DFS (grid, row, col, x-1, y); // bottom DFS (grid, row, col, x + 1, y) ;}; int main () {Solution solution; 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 ;}
Running time