Questão 48: caminho
VoltarConsidere as seguintes definições para representar as posições e movimentos de um robot.
typedef enum movimento {Norte, Oeste, Sul, Este} Movimento;
typedef struct posicao {
int x, y;
} Posicao;
Defina a função int caminho (Posicao inicial, Posicao final, Movimento mov[], int N)
que, dadas as posições inicial e final do robot, preenche o array com os movimentos suficientes para que o robot passe de uma posição para a outra.
A função deverá preencher no máximo N
elementos do array e retornar o número de elementos preenchidos. Se não for possível atingir a posição final com N
movimentos, a função deverá retornar um número negativo.
Exemplo
> Movimento mov[5];
> Posicao inicial = { 0, 0 };
> Posicao final = { 2, -1 };
> caminho(inicial, final, mov, 5)
(int) 3
> mov
(int [5]) { Sul, Este, Este } // por exemplo
Resolução
int caminho (Posicao inicial, Posicao final, Movimento mov[], int N) {
int i;
for(i = 0; i < N; i++) {
if(inicial.x < final.x) {
inicial.x++;
mov[i] = Este;
}
else if (inicial.x > final.x) {
inicial.x--;
mov[i] = Oeste;
}
else if (inicial.y < final.y) {
inicial.y++;
mov[i] = Norte;
}
else if (inicial.y > final.y) {
inicial.y--;
mov[i] = Sul;
}
else break;
}
if(inicial.x != final.x || inicial.y != final.y) return -1;
else return i;
}