See the original problem on HackerRank.
Solutions
We can check each element against its neighbors’ depth and mark it with ‘X’ if the cavity condition is satisfied.
Here is a C++ Solution:
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
|
size_t n;
cin >> n;
vector<vector<char>> data; data.reserve(n);
for (auto i=0u; i<n; ++i)
{
data.emplace_back(n);
copy_n(istream_iterator<char>(cin), n, begin(data[i]));
}
for (auto i=1u; i<n-1; ++i)
{
for (auto j=1u; j<n-1; ++j)
{
auto cavity = data[i][j]-'0';
if (cavity > (data[i][j+1]-'0') &&
cavity > (data[i][j-1]-'0') &&
cavity > (data[i-1][j]-'0') &&
cavity > (data[i+1][j]-'0'))
data[i][j] = 'X';
}
}
for (const auto& row : data)
{
copy(begin(row), end(row), ostream_iterator<char>(cout));
cout << endl;
}
|