GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — leetcode/algorithms/cpp/numberOfIslands/NumberOfIslands.cpp at master · weimo/leetcode Expand file tree/ Copy pathNumberOfIslands.cppMore file actions 104 lines (84 loc) · 2.21 KB / Copy pathNumberOfIslands.cppFile metadata and controls104 lines (84 loc) · 2.21 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 // Source : https://leetcode.com/problems/number-of-islands/ // Author : Hao Chen // Date : 2015-06-08 /********************************************************************************** * * 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 * * Credits:Special thanks to @mithmatt for adding this problem and creating all test cases. * **********************************************************************************/ #include <iostream> #include <vector> using namespace std; void mark(vector<vector<char> >& grid, int r, int c){ if ( r<0 || r>=grid.size() || c<0 || c>=grid[0].size() || grid[r][c] != '1' ) { return; } grid[r][c] = 'M'; //left mark(grid, r, c+1); //right mark(grid, r, c-1); //up mark(grid, r-1, c); //down mark(grid, r+1, c); } int numIslands(vector<vector<char> >& grid) { int result = 0; for (int r=0; r<grid.size(); r++) { for (int c=0; c<grid[r].size(); c++) { if (grid[r][c] == '1') { result++; mark(grid, r, c); } } } return result; } void initGrid( string g[], int len, vector<vector<char> >& grid ) { for (int i=0; i<len; i++){ grid.push_back(vector<char>(g[i].begin(), g[i].end())); } } int main(void) { vector< vector<char> > grid; grid.push_back( vector<char>(1, '1') ); cout << numIslands(grid) << endl; grid.clear(); string g1[] = { "11110", "11010", "11000", "00000" }; initGrid(g1, 4, grid); cout << numIslands(grid) << endl; grid.clear(); string g2[] = { "11000", "11000", "00100", "00011" }; initGrid(g2, 4, grid); cout << numIslands(grid) << endl; return 0; } |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |