0
I have a problem where given a 10x10 matrix, it has to be filled with asterisk characters and the’t'. In this matrix, ONLY the characters with the coordinates that have t' and that are neighboring the coordinates with characters containing asterisk have to be replaced by the character 'p', as shown below:
The code I developed can do the substitution, but it has a problem: it converts all’t' that are located at the left and right end of the matrix. Follow the code below:
using namespace std;
int main()
{
char matriz[10][10];
for(int i=0; i<10; i++)
{
for(int j=0; j<10; j++)
{
cin >> matriz[i][j];
}
}
for(int i=0; i<10; i++)
{
for(int j=0; j<10; j++)
{
if(matriz[i][j] == 't')
{
if(
matriz[i-1][j] == '*' ||
matriz[i+1][j] == '*' ||
matriz[i][j-1] == '*' ||
matriz[i][j+1] == '*')
{
matriz[i][j] = 'p';
}
}
}
}
cout << endl;
for(int i=0; i<10; i++)
{
for(int j=0; j<10; j++)
{
cout << matriz[i][j]<< " ";
}
cout << endl;
}
}
I set up a matrix that shows the problem:
ENTRADA:
* * * t t t * * * *
* * t t t t * * * *
* t t t t t t * * *
* * * * t t t t t t
* * * * * t t t t t
* * * * * t t t * t
* * * * t t t t * *
t t t t t t t t t *
t t t t t t t t * *
t t t t t * * * * *
SAÍDA:
* * * p t p * * * *
* * p t t p * * * *
* p p p t t p * * *
* * * * p t t p p p
* * * * * p t t p p
* * * * * p t p * p
* * * * p t t p * *
p p p p t t t t p *
p t t t t p p p * *
p t t t p * * * * *
As you can see, the’t' in the 4x9 and 8x0 coordinates also changes, which is wrong.
Possibly this is because there is a Matrix Indice burst. If for example the progamma is analyzing the
linha [8,0]
, the conditionmatriz[i][j-1]
looking for a position that does not exist in the casej-1
, that isj = -1
.– Bernardo Lopes