Solución

@alexiis-dev·1/6/2026TypeScript
solution.tsTypeScript
export function generateSpiralMatrix(n: number): number[][] {
const matrix: number[][] = Array.from(
  { length: n },
  () => Array(n).fill(0)
);

let top = 0;
let bottom = n - 1;
let left = 0;
let right = n - 1;
let value = 1

while (top <= bottom && left <= right) {

    for (let col = left; col <= right; col++) {
      matrix[top][col] = value++;
    }
    top++;

    for (let row = top; row <= bottom; row++) {
      matrix[row][right] = value++;
    }
    right--;

    if (top <= bottom) {
      for (let col = right; col >= left; col--) {
        matrix[bottom][col] = value++;
      }
      bottom--;
    }

    if (left <= right) {
      for (let row = bottom; row >= top; row--) {
        matrix[row][left] = value++;
      }
      left++;
    }

}

  return matrix;
}
0respuestas
Respuestas

Aún no hay respuestas

¡Sé el primero en responder!

Escribir un comentario

Recuerda ser amable. Estás comentando la solución de otra persona. Comparte tu perspectiva de forma constructiva y respetuosa.

Debes iniciar sesión para publicar un comentario.