|
| 1 | +// Source : https://leetcode.com/problems/number-of-islands/ |
| 2 | +// Author : Hao Chen |
| 3 | +// Date : 2015-06-08 |
| 4 | + |
| 5 | +/********************************************************************************** |
| 6 | + * |
| 7 | + * Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. |
| 8 | + * An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. |
| 9 | + * You may assume all four edges of the grid are all surrounded by water. |
| 10 | + * |
| 11 | + * Example 1: |
| 12 | + * 11110110101100000000 |
| 13 | + * Answer: 1 |
| 14 | + * Example 2: |
| 15 | + * 11000110000010000011 |
| 16 | + * Answer: 3 |
| 17 | + * |
| 18 | + * Credits:Special thanks to @mithmatt for adding this problem and creating all test cases. |
| 19 | + * |
| 20 | + **********************************************************************************/ |
| 21 | + |
| 22 | +#include <iostream> |
| 23 | +#include <vector> |
| 24 | +using namespace std; |
| 25 | + |
| 26 | +void mark(vector<vector<char> >& grid, int r, int c){ |
| 27 | + if ( r<0 || r>=grid.size() || |
| 28 | + c<0 || c>=grid[0].size() || |
| 29 | + grid[r][c] != '1' ) { |
| 30 | + return; |
| 31 | + } |
| 32 | + |
| 33 | + grid[r][c] = 'M'; |
| 34 | + |
| 35 | + //left |
| 36 | + mark(grid, r, c+1); |
| 37 | + //right |
| 38 | + mark(grid, r, c-1); |
| 39 | + //up |
| 40 | + mark(grid, r-1, c); |
| 41 | + //down |
| 42 | + mark(grid, r+1, c); |
| 43 | +} |
| 44 | + |
| 45 | +int numIslands(vector<vector<char> >& grid) { |
| 46 | + int result = 0; |
| 47 | + for (int r=0; r<grid.size(); r++) { |
| 48 | + for (int c=0; c<grid[r].size(); c++) { |
| 49 | + if (grid[r][c] == '1') { |
| 50 | + result++; |
| 51 | + mark(grid, r, c); |
| 52 | + } |
| 53 | + } |
| 54 | + } |
| 55 | + return result; |
| 56 | +} |
| 57 | + |
| 58 | +void initGrid( string g[], int len, vector<vector<char> >& grid ) |
| 59 | +{ |
| 60 | + for (int i=0; i<len; i++){ |
| 61 | + grid.push_back(vector<char>(g[i].begin(), g[i].end())); |
| 62 | + } |
| 63 | +} |
| 64 | + |
| 65 | +int main(void) |
| 66 | +{ |
| 67 | + vector< vector<char> > grid; |
| 68 | + grid.push_back( vector<char>(1, '1') ); |
| 69 | + |
| 70 | + cout << numIslands(grid) << endl; |
| 71 | + |
| 72 | + |
| 73 | + grid.clear(); |
| 74 | + |
| 75 | + string g1[] = { "11110", |
| 76 | + "11010", |
| 77 | + "11000", |
| 78 | + "00000" }; |
| 79 | + |
| 80 | + initGrid(g1, 4, grid); |
| 81 | + cout << numIslands(grid) << endl; |
| 82 | + |
| 83 | + |
| 84 | + |
| 85 | + grid.clear(); |
| 86 | + |
| 87 | + string g2[] = { "11000", |
| 88 | + "11000", |
| 89 | + "00100", |
| 90 | + "00011" }; |
| 91 | + |
| 92 | + initGrid(g2, 4, grid); |
| 93 | + cout << numIslands(grid) << endl; |
| 94 | + |
| 95 | + |
| 96 | + return 0; |
| 97 | +} |
0 commit comments