-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAmazon_fields_count_in_MxN.cpp
93 lines (83 loc) · 3.3 KB
/
Amazon_fields_count_in_MxN.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
// Alexander Lednev
// 12.11.2019
#include "pch.h"
#include <iostream>
#include <string>
#include <vector>
#include <deque>
#include <assert.h>
using namespace std;
int num_areas(int rows, int columns, vector<int> data) {
vector<int> entered(data.size(), 0);
struct point {
int x, y;
explicit point(int __x, int __y) : x(__x), y(__y) { }
};
deque<point> indexes;
int count = 0;
for (int y = 0; y < rows; ++y) {
for (int x = 0; x < columns; ++x) {
if (entered[y*columns + x] == 0) {
entered[y*columns + x] = 1;
if (data[y*columns + x] == 1) {
++count;
{
const int next_x = x + 1;
const int next_y = y + 1;
if (next_x < columns && entered[next_x + y * columns] == 0) {
assert(next_x < columns && y < rows);
indexes.emplace_back(next_x, y);
}
if (next_y < rows && entered[x + next_y * columns] == 0) {
assert(x < columns && next_y < rows);
indexes.emplace_back(x, next_y);
}
}
while (!indexes.empty()) {
auto const P = indexes.front(); indexes.pop_front();
if (entered[P.x + P.y * columns] == 0) {
entered[P.x + P.y * columns] = 1;
if (data[P.x + P.y * columns] == 1) {
const int next_x = P.x + 1;
const int prev_x = P.x - 1;
const int next_y = P.y + 1;
const int prev_y = P.y - 1;
if (next_x < columns && entered[next_x + P.y * columns] == 0) {
assert(next_x < columns && P.y < rows);
indexes.emplace_back(next_x, P.y);
}
if (next_y < rows && entered[P.x + next_y * columns] == 0) {
assert(P.x < columns && next_y < rows);
indexes.emplace_back(P.x, next_y);
}
if (prev_x >= 0 && entered[prev_x + P.y * columns] == 0) {
assert(prev_x < columns && P.y < rows);
indexes.emplace_back(prev_x, P.y);
}
if (prev_y >= 0 && entered[P.x + prev_y * columns] == 0) {
assert(P.x < columns && prev_y < rows);
indexes.emplace_back(P.x, prev_y);
}
}
}
}
}
}
}
}
return count;
}
int main()
{
vector<int> areas =
{
1, 0, 0, 1, 1, 1, 1,
1, 0, 1, 0, 0, 1, 0,
1, 0, 0, 1, 0, 1, 1,
1, 1, 1, 1, 0, 0, 0,
0, 0, 0, 0, 0, 1, 0,
0, 0, 0, 0, 0, 0, 1,
};
cout << "ANS: " << num_areas(6, 7, areas);
return 0;
}