From a7a712a5da19b0588c220390d1806e60b0dcf956 Mon Sep 17 00:00:00 2001 From: chayan das <110921638+Chayandas07@users.noreply.github.com> Date: Fri, 31 Jan 2025 16:08:47 +0530 Subject: [PATCH] Create 827. Making A Large Island --- 827. Making A Large Island | 70 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 827. Making A Large Island diff --git a/827. Making A Large Island b/827. Making A Large Island new file mode 100644 index 0000000..2c6263a --- /dev/null +++ b/827. Making A Large Island @@ -0,0 +1,70 @@ +class Solution { +public: + int largestIsland(vector>& grid) { + if (grid.empty()) + return 0; + + int n = grid.size(); + vector> labels(n,vector(n, 0)); + unordered_map islandSizes; + int label = 1; + int maxSize = 0; + + int dirs[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; + + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + if (grid[i][j] == 1 && labels[i][j] == 0) { + int size = 0; + vector> stack; + stack.push_back({i, j}); + labels[i][j] = label; + + while (!stack.empty()) { + auto [x, y] = stack.back(); + stack.pop_back(); + size++; + + for (auto [dx, dy] : dirs) { + int nx = x + dx, ny = y + dy; + if (nx >= 0 && nx < n && ny >= 0 && ny < n && + grid[nx][ny] == 1 && labels[nx][ny] == 0) { + labels[nx][ny] = label; + stack.push_back({nx, ny}); + } + } + } + + islandSizes[label] = size; + maxSize = max(maxSize, size); + label++; + } + } + } + + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + if (grid[i][j] == 0) { + unordered_set neighborLabels; + int total = 1; + + for (auto [dx, dy] : dirs) { + int nx = i + dx, ny = j + dy; + if (nx >= 0 && nx < n && ny >= 0 && ny < n && + grid[nx][ny] == 1) { + neighborLabels.insert(labels[nx][ny]); + } + } + + for (int lbl : neighborLabels) { + total += islandSizes[lbl]; + } + + maxSize = max(maxSize, total); + } + } + } + + return maxSize; + } +};