-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathctci-connected-cell-in-a-grid.cpp
75 lines (61 loc) · 2.33 KB
/
ctci-connected-cell-in-a-grid.cpp
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
// DFS: Connected Cell in a Grid
// Find the largest connected region in a 2D Matrix.
//
// https://www.hackerrank.com/challenges/ctci-connected-cell-in-a-grid/problem
//
#include <bits/stdc++.h>
using namespace std;
struct coord
{
int x;
int y;
};
int get_biggest_region(int n, int m, vector<vector<int>>& grid)
{
int size_max = 0;
for (int x = 0; x < n; ++x)
{
for (int y = 0; y < m; ++y)
{
if (grid[x][y] == 1)
{
stack<coord> fill;
fill.push(coord{x, y});
int size = 0;
while (! fill.empty())
{
coord p = fill.top();
fill.pop();
if (grid[p.x][p.y] != 1) continue;
grid[p.x][p.y] = 2;
size++;
if (p.x > 0 && p.y > 0 && grid[p.x - 1][p.y - 1] == 1) fill.push(coord{p.x - 1, p.y - 1});
if (p.x > 0 && grid[p.x - 1][p.y ] == 1) fill.push(coord{p.x - 1, p.y });
if (p.x > 0 && p.y < m-1 && grid[p.x - 1][p.y + 1] == 1) fill.push(coord{p.x - 1, p.y + 1});
if (p.x < n-1 && p.y > 0 && grid[p.x + 1][p.y - 1] == 1) fill.push(coord{p.x + 1, p.y - 1});
if (p.x < n-1 && grid[p.x + 1][p.y ] == 1) fill.push(coord{p.x + 1, p.y });
if (p.x < n-1 && p.y < m-1 && grid[p.x + 1][p.y + 1] == 1) fill.push(coord{p.x + 1, p.y + 1});
if ( p.y > 0 && grid[p.x ][p.y - 1] == 1) fill.push(coord{p.x , p.y - 1});
if ( p.y < m-1 && grid[p.x ][p.y + 1] == 1) fill.push(coord{p.x , p.y + 1});
}
if (size > size_max)
size_max = size;
}
}
}
return size_max;
}
int main(){
int n;
cin >> n;
int m;
cin >> m;
vector<vector<int>> grid(n,vector<int>(m));
for(int grid_i = 0;grid_i < n;grid_i++){
for(int grid_j = 0;grid_j < m;grid_j++){
cin >> grid[grid_i][grid_j];
}
}
cout << get_biggest_region(n, m, grid) << endl;
return 0;
}