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
| #include <iostream> #include <algorithm> #include <vector> #include <unordered_map> #include <string>
using namespace std;
class Solution { int cnt; public: int m; int island; unordered_map<int, int> map;
void helper(int row, int col, vector<vector<char>>& grid) { if(row<0 || row>= grid.size() || col<0 || col>=grid[0].size() || grid[row][col]=='0') return; if(grid[row][col]=='1') { cnt++; grid[row][col] = '0'; helper(row-1, col, grid); helper(row, col-1, grid); helper(row+1, col, grid); helper(row, col+1, grid); } return; } int numIslands(vector<vector<char>>& grid) { int rows = grid.size(); int cols = grid[0].size(); m =0; island = 0; for(int row = 0; row < rows; row++) { for(int col = 0; col < cols; col++) { if(grid[row][col]=='1') { island++; cnt=0; helper(row, col, grid); m = max(cnt, m); if(map.find(cnt) == map.end()) { map[cnt] = 1; } else { map[cnt]++; } } } } return island; } };
int main () { Solution s; vector<vector<char>> m { {'1','0','1','0','1'}, {'1','1','0','1','0'}, {'1','1','0','1','1'}, {'0','0','0','0','1'} };
cout<<"island cnt: "<<s.numIslands(m)<<endl; cout<<"max island: "<<s.m<<endl; cout<<"island shape map: "<<endl; for (auto item: s.map) { cout<<"shape: "<< item.first<<", cnt: "<< item.second<<endl; }
return 0; }
|