mirror of
https://github.com/20kaushik02/leetcode-gulag.git
synced 2026-01-25 07:34:05 +00:00
day 33: 200-number-of-islands, 141-linked-list-cycle
This commit is contained in:
13
200-number-of-islands/driver.cpp
Normal file
13
200-number-of-islands/driver.cpp
Normal file
@@ -0,0 +1,13 @@
|
||||
#include "soln.hpp"
|
||||
|
||||
int main()
|
||||
{
|
||||
vector<vector<char>> grid{{'1', '1', '1', '1', '0'},
|
||||
{'1', '1', '0', '1', '0'},
|
||||
{'1', '1', '1', '0', '1'},
|
||||
{'0', '0', '0', '1', '1'}};
|
||||
int answer = 2;
|
||||
Solution soln;
|
||||
cout << "Found no. of islands correctly? " << soln.test(grid, answer) << endl;
|
||||
return 0;
|
||||
}
|
||||
52
200-number-of-islands/soln.cpp
Normal file
52
200-number-of-islands/soln.cpp
Normal file
@@ -0,0 +1,52 @@
|
||||
#include "soln.hpp"
|
||||
|
||||
int Solution::numIslands(vector<vector<char>> &grid)
|
||||
{
|
||||
// queue<pair<int,int>> current_island{pair<int,int>{0,0}};
|
||||
int islands = 0;
|
||||
for (int i = 0; i < grid.size(); i++)
|
||||
{
|
||||
for (int j = 0; j < grid[0].size(); j++)
|
||||
{
|
||||
// found land
|
||||
if (grid[i][j] == '1')
|
||||
{
|
||||
islands++;
|
||||
grid[i][j] = '0';
|
||||
queue<pair<int, int>> adjs;
|
||||
adjs.push({i, j});
|
||||
while (!adjs.empty())
|
||||
{
|
||||
pair<int, int> adj = adjs.front();
|
||||
adjs.pop();
|
||||
if (adj.first + 1 < grid.size() && grid[adj.first + 1][adj.second] == '1')
|
||||
{
|
||||
grid[adj.first + 1][adj.second] = '0';
|
||||
adjs.push({adj.first + 1, adj.second});
|
||||
}
|
||||
if (adj.first > 0 && grid[adj.first - 1][adj.second] == '1')
|
||||
{
|
||||
grid[adj.first - 1][adj.second] = '0';
|
||||
adjs.push({adj.first - 1, adj.second});
|
||||
}
|
||||
if (adj.second + 1 < grid[0].size() && grid[adj.first][adj.second + 1] == '1')
|
||||
{
|
||||
grid[adj.first][adj.second + 1] = '0';
|
||||
adjs.push({adj.first, adj.second + 1});
|
||||
}
|
||||
if (adj.second > 0 && grid[adj.first][adj.second - 1] == '1')
|
||||
{
|
||||
grid[adj.first][adj.second - 1] = '0';
|
||||
adjs.push({adj.first, adj.second - 1});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return islands;
|
||||
}
|
||||
|
||||
bool Solution::test(vector<vector<char>> &grid, int answer)
|
||||
{
|
||||
return numIslands(grid) == answer;
|
||||
}
|
||||
8
200-number-of-islands/soln.hpp
Normal file
8
200-number-of-islands/soln.hpp
Normal file
@@ -0,0 +1,8 @@
|
||||
#include <bits/stdc++.h>
|
||||
using namespace std;
|
||||
class Solution
|
||||
{
|
||||
public:
|
||||
int numIslands(vector<vector<char>> &grid);
|
||||
bool test(vector<vector<char>> &grid, int answer);
|
||||
};
|
||||
Reference in New Issue
Block a user