Solución

@zavaladereck77_945e239f·hace 23hTypeScript
solution.tsTypeScript
export function generateSpiralMatrix(n: number): number[][] {
  // Escribe tu solución aquí
  // const matrix = Array( n ).fill( Array( n ).fill( 0 ) )
  const matrix = Array.from({ length: n }, () => Array( n ).fill( 0 ))
  let top = 0
  let bottom = n - 1
  let left = 0
  let right = n - 1
  let counter = 1

  while( top <= bottom && left <= right ) {
    for ( let i = left; i <= right; i++ ) {
      matrix[top][i] = counter
      counter++
    }
    top++

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

    for ( let i = right; i >= left; i-- ) {
      matrix[bottom][i] = counter
      counter++
    }
    bottom--

    for ( let i = bottom; i >= top; i-- ) {
      matrix[i][left] = counter
      counter++
    }
    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.