Skip to content

Commit

Permalink
impl number of islands
Browse files Browse the repository at this point in the history
  • Loading branch information
SKTT1Ryze committed Mar 19, 2024
1 parent 9a1cafa commit bd6562e
Showing 1 changed file with 47 additions and 7 deletions.
54 changes: 47 additions & 7 deletions leetcode-cc/NumOfIslands.hpp
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#include <unordered_set>
#include <utility>

#include "PairHash.h"
#include "TestHelper.h"
Expand All @@ -23,21 +24,60 @@ class SNumOfIslands : public ISolution {
int test() const override {
return testHelper<vector<vector<char>>, int>(
{{
{'1', '1', '1', '1', '0'},
{'1', '1', '0', '1', '0'},
{'1', '1', '0', '0', '0'},
{'0', '0', '0', '0', '0'},
}},
{1}, [this](auto input) { return this->numIslands(input); });
{'1', '1', '1', '1', '0'},
{'1', '1', '0', '1', '0'},
{'1', '1', '0', '0', '0'},
{'0', '0', '0', '0', '0'},
},
{
{'1', '1', '0', '0', '0'},
{'1', '1', '0', '0', '0'},
{'0', '0', '1', '0', '0'},
{'0', '0', '0', '1', '1'},
}},
{1, 3}, [this](auto input) { return this->numIslands(input); });
};
int benchmark() const override { return 0; }

private:
int numIslands(vector<vector<char>>& grid) const {
int m = grid.size();
int n = grid[0].size();

pair<int, int> p = {0, 0};

while (p.first < m && p.second < n) {
if (grid[p.first][p.second] == '1') break;
p = nextPair(p, m, n);
}

int res = 0;
unordered_set<pair<int, int>, pair_hash> set = {};

while (p.first < m && p.second < n) {
if (!set.contains(p) && grid[p.first][p.second] == '1') {
dfs(grid, p.first, p.second, set);
res++;
}
p = nextPair(p, m, n);
}

return res;
}

static void dfs(vector<vector<char>>& grid, int row, int col,
unordered_set<pair<int, int>, pair_hash>) {}
unordered_set<pair<int, int>, pair_hash>& set) {
if (!set.contains({row, col}) && grid[row][col] == '1') {
set.insert({row, col});
if (row > 0) dfs(grid, row - 1, col, set);
if (row < grid.size() - 1) dfs(grid, row + 1, col, set);
if (col > 0) dfs(grid, row, col - 1, set);
if (col < grid[0].size() - 1) dfs(grid, row, col + 1, set);
}
}

static pair<int, int> nextPair(pair<int, int> p, int m, int n) {
return (p.second == n - 1) ? make_pair(p.first + 1, 0)
: make_pair(p.first, p.second + 1);
}
};

0 comments on commit bd6562e

Please sign in to comment.