aboutsummaryrefslogtreecommitdiff
path: root/04_graph_algorithms/counting_rooms_1192.cpp
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--04_graph_algorithms/counting_rooms_1192.cpp62
1 files changed, 62 insertions, 0 deletions
diff --git a/04_graph_algorithms/counting_rooms_1192.cpp b/04_graph_algorithms/counting_rooms_1192.cpp
new file mode 100644
index 0000000..dc71529
--- /dev/null
+++ b/04_graph_algorithms/counting_rooms_1192.cpp
@@ -0,0 +1,62 @@
1#include <iostream>
2#include <string>
3#include <vector>
4
5class Tile {
6public:
7 int i;
8 int j;
9 std::vector<Tile> neighbors() const {
10 return {Tile{i-1,j}, Tile{i+1,j}, Tile{i,j-1}, Tile{i,j+1}};
11 }
12};
13
14class Map {
15public:
16 int n;
17 int m;
18
19 Map(int i, int j) : n{i}, m{j}, c(n*m, 0) {}
20 int color(Tile t) const { return inbound(t) ? c[ind(t)] : -1; }
21 void setcolor(Tile t, int k) { if (inbound(t)) c[ind(t)] = k; }
22 bool wall(Tile t) const { return !inbound(t) || c[ind(t)] == -1; }
23 void setwall(Tile t) { if (inbound(t)) setcolor(t, -1); }
24private:
25 std::vector<int> c;
26
27 size_t ind(Tile t) const { return m*t.i + t.j; }
28 bool inbound(Tile t) const {
29 return t.i >= 0 && t.i < n && t.j >= 0 && t.j < m;
30 }
31};
32
33Map readmap() {
34 int n, m;
35 std::string s;
36 std::cin >> n >> m;
37 Map map(n, m);
38 for (int i = 0; i < n; i++) {
39 std::cin >> s;
40 for (int j = 0; j < m; j++)
41 if (s[j] == '#')
42 map.setwall(Tile{i, j});
43 }
44 return map;
45}
46
47void visit(Map& m, Tile t, int c) {
48 m.setcolor(t, c);
49 for (auto u : t.neighbors())
50 if (m.color(u) == 0)
51 visit(m, u, c);
52}
53
54int main() {
55 auto m = readmap();
56 int c{0};
57 for (int i = 0; i < m.n; i++)
58 for (int j = 0; j < m.m; j++)
59 if (m.color(Tile{i, j}) == 0)
60 visit(m, Tile{i, j}, ++c);
61 std::cout << c << "\n";
62}

Generated with cgit - Back to sebastiano.tronto.net