You are given a square n×n map. Each cell of the map has a value in it denoting the depth of the appropriate area. We will call a cell of the map a cavity if and only if this cell is not on the border of the map and each cell adjacent to it has strictly smaller depth. Two cells are adjacent if they have a common side.
You need to find all the cavities on the map and depict them with character X.
Input Format
The first line contains an integer n (1≤n≤100), denoting the size of the map. Each of the following n lines contains n positive digits without spaces. A digit (1-9) denotes the depth of the appropriate area.
Output Format
Output n lines, denoting the resulting map. Each cavity should be replaced with character X.
Sample Input
4
1112
1912
1892
1234
Sample Output
1112
1X12
18X2
1234
Now, I made this code. But this shows incorrect answer for large values, that is the value of n being 99 or 100 or 96.
This basically takes the input number and divides each row of the input array into individual digits. Then it compares each digit with the next and previous digit to check if it is greater than or less than the considered digit. However, it shows wrong answer for large values of n
.
Here is the working code. ( Works fine on sample input )
#include <iostream>
#include <cmath>
#include <cstdio>
using namespace std;
int main(void) {
int n, i = 0;
cin >> n;
int values[1000];
int j;
for (i = 0; i < n; i++) {
int p;
cin >> p;
values[i] = p;
}
char digits[1000][1000];
int foo;
for (i = 0; i < n; i++) {
foo = n - 1;
while (values[i] != 0) {
digits[i][foo] = values[i] % 10 + 48;
values[i] = values[i] / 10;
foo--;
}
}
for (i = 1; i < n - 1; i++) {
j = 1;
while (j != n - 1) {
if (digits[i][j] > digits[i][j - 1] &&
digits[i][j] > digits[i][j + 1]) {
digits[i][j] = 'X';
}
j++;
}
}
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
printf("%c", digits[i][j]);
}
printf("\n");
}
return 0;
}
This shows incorrect answer for large values of the input such as the value of n
being 96
or 100
. I don't understand why? Is there any way I can optimize it?
Not working for the above input.
PS: This is not a homework question. I am not able to guess how to solve it.