How to check the elements close to a specific element in a matrix?

Asked

Viewed 98 times

0

The goal is to try to find on the college campus possible locations for building a new building. The user will enter the matrix representing the college plan.

R = Ruas
P = Prédios
V = Área Verde
E = Estacionamento

R R R R R R R R R R R R       
R V V V V V V V V E E E   
R V P V V V P V V E E E   
R V V V V V V V V E E E   
R V V V V V V V V V V V   
R V V V V V P V V V P V   
R V P V V V V V V V V V   
R V V V V V V V V V V V   
R E E E E E E E E E E V  
R E E E E E E E E E E V   
R E E E E E E E E E E V  
R R R R R R R R R R R R  

After receiving this user matrix, the program will mark with the letter N (New) all possible positions for the new building. The rules for the positioning of the new building are: it cannot be next to streets, parking lots or other buildings, that is, only in positions surrounded by green areas as in the example below:

V V V   
V N V  
V V V

At the end of the process present to the user the matrix with the letter N in all possible

**I’m a beginner in programming in general, and would like tips on how to do this algorithm(Mainly on how to check which elements have green area around).

1 answer

1

If you put the campus in a matrix, the most direct method (brute force) works well

char campus[MAXROWS][MAXCOLS];

// input, preenche campus, obtem nrows e ncols

// para todos os elementos que nao estao na borda do campus
for (row = 1; row < nrows - 1; row++) {
    for (col = 1; col < ncols - 1; col++) {
        totalNV = 0;
        // conta N e V para todos os elementos da area 3x3 centrada em (row, col)
        for (i = -1; i < 2; i++) {
            for (j = -1; j < 2; j++) {
                if (campus[row + i][col + j] == 'N') totalNV++;
                if (campus[row + i][col + j] == 'V') totalNV++;
            }
        }
        if (totalNV == 9) campus[row][col] = 'N';
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.