-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday45.cpp
More file actions
80 lines (62 loc) · 2.08 KB
/
day45.cpp
File metadata and controls
80 lines (62 loc) · 2.08 KB
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
76
77
78
79
80
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
struct State {
int x, y, civilians;
};
int dx[] = {-1, 1, 0, 0}; // Directions for moving up, down, left, and right
int dy[] = {0, 0, -1, 1};
bool isValid(int x, int y, int n, vector<vector<int>>& grid, vector<vector<bool>>& visited) {
return x >= 0 && x < n && y >= 0 && y < n && grid[x][y] != 2 && !visited[x][y];
}
int maxCiviliansRescued(vector<vector<int>>& grid, int n) {
int maxCivilians = 0;
vector<vector<bool>> visited(n, vector<bool>(n, false));
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] == 1 && !visited[i][j]) {
// BFS to calculate civilians rescued from this starting point
queue<State> q;
q.push({i, j, 0});
vector<vector<bool>> localVisited(n, vector<bool>(n, false));
localVisited[i][j] = true;
int civilians = 0;
while (!q.empty()) {
State current = q.front();
q.pop();
if (grid[current.x][current.y] == 1) {
civilians++;
}
for (int dir = 0; dir < 4; ++dir) {
int nx = current.x + dx[dir];
int ny = current.y + dy[dir];
if (isValid(nx, ny, n, grid, localVisited)) {
localVisited[nx][ny] = true;
q.push({nx, ny, civilians});
}
}
}
maxCivilians = max(maxCivilians, civilians);
}
}
}
return maxCivilians;
}
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<vector<int>> grid(n, vector<int>(n));
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
cin >> grid[i][j];
}
}
cout << maxCiviliansRescued(grid, n) << endl;
}
return 0;
}