Programa para imprimir Patrón Espiral

Dado un número n como el tamaño de la array, la tarea es imprimir un patrón en espiral en una array 2D de tamaño n.

Ejemplos: 

Input: n = 5
Output:   1   2   3   4   5
          16  17  18  19  6
          15  24  25  20  7
          14  23  22  21  8
          13  12  11  10  9

Vista previa del patrón en espiral:
 

Acercarse: 

  1. Crear una array 2D de tamaño n
  2. Almacene el límite de la array en la variable de límite. Inicialmente será n-1 y luego cambiará después de cada rotación.
  3. Guarde el tamaño restante para la impresión en espiral en variable sizeLeft. Inicialmente será n-1 y luego decrecerá en 1 cada 2 rotaciones.
  4. Cree una bandera para determinar 2 rotaciones, ya que después de cada 2 rotaciones, el tamaño a la izquierda disminuirá.
  5. Cree un movimiento de variable char para almacenar el movimiento actual del patrón en espiral. Puede tener ‘r’ para derecha, ‘l’ para izquierda, ‘d’ para abajo y ‘u’ para arriba.
  6. Repita los pasos a continuación hasta que ‘i’ esté en el rango [1, n ^ 2]: 
    • Asigne el valor de i al patrón en espiral.
    • Determine el siguiente movimiento del patrón.
    • Verifique que el patrón alcance el límite. Si se alcanza, modifique los tamaños y gire el patrón en espiral.
  7. Imprima el patrón en espiral almacenado en la array 2D.

A continuación se muestra la implementación de Java del enfoque anterior: 

C++

#include <iostream>
using namespace std;
 
void printSpiral(int size)
{
 
    // Create row and col
    // to traverse rows and columns
    int row = 0, col = 0;
 
    int boundary = size - 1;
    int sizeLeft = size - 1;
    int flag = 1;
 
    // Variable to determine the movement
    // r = right, l = left, d = down, u = upper
    char move = 'r';
 
    // Array for matrix
    int matrix[size][size] = {0};
 
    for (int i = 1; i < size * size + 1; i++)
    {
 
        // Assign the value
        matrix[row][col] = i;
 
        // switch-case to determine the next index
        switch (move)
        {
 
            // If right, go right
            case 'r':
                col += 1;
                break;
     
            // if left, go left
            case 'l':
                col -= 1;
                break;
     
            // if up, go up
            case 'u':
                row -= 1;
                break;
     
            // if down, go down
            case 'd':
                row += 1;
                break;
        }
 
        // Check if the matrix
        // has reached array boundary
        if (i == boundary)
        {
 
            // Add the left size for the next boundary
            boundary += sizeLeft;
 
            // If 2 rotations has been made,
            // decrease the size left by 1
            if (flag != 2)
            {
 
                flag = 2;
            }
            else
            {
 
                flag = 1;
                sizeLeft -= 1;
            }
 
            // switch-case to rotate the movement
            switch (move)
            {
 
                // if right, rotate to down
                case 'r':
                    move = 'd';
                    break;
     
                // if down, rotate to left
                case 'd':
                    move = 'l';
                    break;
     
                // if left, rotate to up
                case 'l':
                    move = 'u';
                    break;
     
                // if up, rotate to right
                case 'u':
                    move = 'r';
                    break;
            }
        }
    }
 
    // Print the matrix
    for (row = 0; row < size; row++)
    {
        for (col = 0; col < size; col++)
        {
 
            int n = matrix[row][col];
            if(n < 10)
                cout << n << " ";
            else
                cout << n << " ";
        }
 
        cout << endl;
    }
}
 
// Driver Code
int main()
{
 
    // Get the size of size
    int size = 5;
 
    // Print the Spiral Pattern
    printSpiral(size);
    return 0;
}
 
// This code is contributed by 29AjayKumar

Java

public class GFG {
 
    public static void printSpiral(int size)
    {
 
        // Create row and col
        // to traverse rows and columns
        int row = 0, col = 0;
 
        int boundary = size - 1;
        int sizeLeft = size - 1;
        int flag = 1;
 
        // Variable to determine the movement
        // r = right, l = left, d = down, u = upper
        char move = 'r';
 
        // Array  for matrix
        int matrix[][] = new int[size][size];
 
        for (int i = 1; i < size * size + 1; i++) {
 
            // Assign the value
            matrix[row][col] = i;
 
            // switch-case to determine the next index
            switch (move) {
 
            // If right, go right
            case 'r':
                col += 1;
                break;
 
            // if left, go left
            case 'l':
                col -= 1;
                break;
 
            // if up, go up
            case 'u':
                row -= 1;
                break;
 
            // if down, go down
            case 'd':
                row += 1;
                break;
            }
 
            // Check if the matrix
            // has reached array boundary
            if (i == boundary) {
 
                // Add the left size for the next boundary
                boundary += sizeLeft;
 
                // If 2 rotations has been made,
                // decrease the size left by 1
                if (flag != 2) {
 
                    flag = 2;
                }
                else {
 
                    flag = 1;
                    sizeLeft -= 1;
                }
 
                // switch-case to rotate the movement
                switch (move) {
 
                // if right, rotate to down
                case 'r':
                    move = 'd';
                    break;
 
                // if down, rotate to left
                case 'd':
                    move = 'l';
                    break;
 
                // if left, rotate to up
                case 'l':
                    move = 'u';
                    break;
 
                // if up, rotate to right
                case 'u':
                    move = 'r';
                    break;
                }
            }
        }
 
        // Print the matrix
        for (row = 0; row < size; row++) {
            for (col = 0; col < size; col++) {
 
                int n = matrix[row][col];
                System.out.print((n < 10)
                                     ? (n + "  ")
                                     : (n + " "));
            }
 
            System.out.println();
        }
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        // Get the size of size
        int size = 5;
 
        // Print the Spiral Pattern
        printSpiral(size);
    }
}

C#

// C# implementation of the approach
using System;
 
class GFG {
 
    public static void printSpiral(int size)
    {
 
        // Create row and col
        // to traverse rows and columns
        int row = 0, col = 0;
 
        int boundary = size - 1;
        int sizeLeft = size - 1;
        int flag = 1;
 
        // Variable to determine the movement
        // r = right, l = left, d = down, u = upper
        char move = 'r';
 
        // Array for matrix
        int[, ] matrix = new int[size, size];
 
        for (int i = 1; i < size * size + 1; i++) {
 
            // Assign the value
            matrix[row, col] = i;
 
            // switch-case to determine the next index
            switch (move) {
 
            // If right, go right
            case 'r':
                col += 1;
                break;
 
            // if left, go left
            case 'l':
                col -= 1;
                break;
 
            // if up, go up
            case 'u':
                row -= 1;
                break;
 
            // if down, go down
            case 'd':
                row += 1;
                break;
            }
 
            // Check if the matrix
            // has reached array boundary
            if (i == boundary) {
 
                // Add the left size for the next boundary
                boundary += sizeLeft;
 
                // If 2 rotations has been made,
                // decrease the size left by 1
                if (flag != 2) {
 
                    flag = 2;
                }
                else {
 
                    flag = 1;
                    sizeLeft -= 1;
                }
 
                // switch-case to rotate the movement
                switch (move) {
 
                // if right, rotate to down
                case 'r':
                    move = 'd';
                    break;
 
                // if down, rotate to left
                case 'd':
                    move = 'l';
                    break;
 
                // if left, rotate to up
                case 'l':
                    move = 'u';
                    break;
 
                // if up, rotate to right
                case 'u':
                    move = 'r';
                    break;
                }
            }
        }
 
        // Print the matrix
        for (row = 0; row < size; row++) {
            for (col = 0; col < size; col++) {
 
                int n = matrix[row, col];
                Console.Write((n < 10)
                                  ? (n + " ")
                                  : (n + " "));
            }
 
            Console.WriteLine();
        }
    }
 
    // Driver Code
    public static void Main(String[] args)
    {
 
        // Get the size of size
        int size = 5;
 
        // Print the Spiral Pattern
        printSpiral(size);
    }
}
 
/* This code contributed by PrinciRaj1992 */

Javascript

<script>
 
function printSpiral(size)
{
     
    // Create row and col
    // to traverse rows and columns
    let row = 0, col = 0;
 
    let boundary = size - 1;
    let sizeLeft = size - 1;
    let flag = 1;
 
    // Variable to determine the movement
    // r = right, l = left, d = down, u = upper
    let move = 'r';
 
    // Array for matrix
    let matrix = new Array(size);
    for(let i = 0; i < size; i++)
    {
        matrix[i] = new Array(size).fill(0);
    }
 
    for(let i = 1; i < size * size + 1; i++)
    {
         
        // Assign the value
        matrix[row][col] = i;
 
        // switch-case to determine
        // the next index
        switch (move)
        {
             
            // If right, go right
            case 'r':
                col += 1;
                break;
     
            // If left, go left
            case 'l':
                col -= 1;
                break;
     
            // If up, go up
            case 'u':
                row -= 1;
                break;
     
            // If down, go down
            case 'd':
                row += 1;
                break;
        }
 
        // Check if the matrix
        // has reached array boundary
        if (i == boundary)
        {
 
            // Add the left size for the
            // next boundary
            boundary += sizeLeft;
 
            // If 2 rotations has been made,
            // decrease the size left by 1
            if (flag != 2)
            {
                flag = 2;
            }
            else
            {
                flag = 1;
                sizeLeft -= 1;
            }
 
            // switch-case to rotate the movement
            switch (move)
            {
                 
                // If right, rotate to down
                case 'r':
                    move = 'd';
                    break;
     
                // If down, rotate to left
                case 'd':
                    move = 'l';
                    break;
     
                // If left, rotate to up
                case 'l':
                    move = 'u';
                    break;
     
                // If up, rotate to right
                case 'u':
                    move = 'r';
                    break;
            }
        }
    }
 
    // Print the matrix
    for(row = 0; row < size; row++)
    {
        for(col = 0; col < size; col++)
        {
            let n = matrix[row][col];
            if (n < 10)
                document.write(n + " ");
            else
                document.write(n + " ");
        }
        document.write("<br>");
    }
}
 
// Driver Code
 
// Get the size of size
let size = 5;
 
// Print the Spiral Pattern
printSpiral(size);
 
// This code is contributed by subham348
 
</script>
Producción: 

1  2  3  4  5  
16 17 18 19 6  
15 24 25 20 7  
14 23 22 21 8  
13 12 11 10 9

 

Complejidad temporal : O(m*n) donde m es el número de filas y n es el número de columnas de una array dada

Publicación traducida automáticamente

Artículo escrito por zeph y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *