From 6e0d9d8176a32fde6bf5939ca7cd996e247f4276 Mon Sep 17 00:00:00 2001 From: juan Date: Sat, 16 Jul 2022 08:59:20 +0800 Subject: [PATCH] vault backup: 2022-07-16 08:59:20 --- OJ notes/pages/Leetcode Max-Area-of-Island.md | 48 ++++++++++++++++++- 1 file changed, 47 insertions(+), 1 deletion(-) diff --git a/OJ notes/pages/Leetcode Max-Area-of-Island.md b/OJ notes/pages/Leetcode Max-Area-of-Island.md index 0602ad5..640642f 100644 --- a/OJ notes/pages/Leetcode Max-Area-of-Island.md +++ b/OJ notes/pages/Leetcode Max-Area-of-Island.md @@ -68,6 +68,11 @@ We keep track of pile we visited, using: - an 2-d bool vector visited(which is the one I'm using) - change the value of pile to 0 +and check for: +- x, y is not OOB +- x, y is in a island -> (value == 1) +- x, y is not visited (see above) + And for each unvisited pile, run DFS or BFS to check the size, and keep track of max size with a variable ### Solution @@ -203,4 +208,45 @@ public: }; ``` -DFS recursive \ No newline at end of file +DFS recursive +```cpp +class Solution { + // DFS recursive + int getSize(vector> &grid, int m, int n, int x, int y, + vector> &visited) { + if (x >= 0 && x < m && y >= 0 && y < n && !visited[x][y] && + grid[x][y] == 1) { + visited[x][y] = true; + return 1 + getSize(grid, m, n, x + 1, y, visited) + + getSize(grid, m, n, x - 1, y, visited) + + getSize(grid, m, n, x, y + 1, visited) + + getSize(grid, m, n, x, y - 1, visited); + } else { + return 0; + } + } + +public: + int maxAreaOfIsland(vector> &grid) { + int m = grid.size(), n = grid[0].size(); + int maxSize = 0; + + vector> visited; + for (int i = 0; i < m; i++) { + visited.push_back({}); + for (int j = 0; j < n; j++) { + visited.back().push_back(false); + } + } + + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (grid[i][j] == 1 && !visited[i][j]) { + maxSize = max(maxSize, getSize(grid, m, n, i, j, visited)); + } + } + } + return maxSize; + } +}; +``` \ No newline at end of file