Spiral matrix does not work Java

1

This is the code I did to go through the spiral matrix, but it goes through the matrix in a different way

2000021 
1970022 
1860123
1714131224 
1600025
public class caracol {
   public static void main(String[] args) {
int[][] matriz = new int[5][5];
int n=5;
int nlimite= n-1;
int inicio = 0;
int c=1;
while(c<=(n*n)){

            for (int i = inicio+2; i<=nlimite-1; i++) //baja
            {
                matriz[i][nlimite-1] = c++;

            }

            for (int i = inicio+2; i>=inicio+1; i--) ///izquierda
            {
                matriz[nlimite-1][i] = c++;

            }

            for (int i = nlimite-1; i>=inicio+1; i--) //sube
            {
                matriz[i][inicio+1] = c++;

            }


            for (int i = inicio+1; i>=nlimite-1; i++) //derecha
            {
                matriz[inicio+1][i] = c++;

            }

           for (int i = inicio+1; i<=nlimite; i++) //baja
            {
                matriz[i][nlimite] = c++;

            }

             for (int i = nlimite-1; i>=inicio; i--) ///izquierda
            {
                matriz[nlimite-1][i] = c++;

            }

            for (int i = nlimite; i>=inicio; i--) //sube
            {
                matriz[i][inicio] = c++;

            }

            for (int i = inicio; i>=nlimite; i++) //derecha
            {
                matriz[inicio][i] = c++;

            }  

            for (int i = inicio; i<=nlimite; i++) //baja
            {
                matriz[i][nlimite] = c++;

            }
            nlimite=nlimite-1;
inicio = inicio+1;
}
for(int x=0;x<n;x++){ /*Mostrar la matriz en pantalla*/
System.out.println();
for(int y=0;y<n;y++){
System.out.print(matriz[x][y]);
}
}
} 
}
    
asked by ives rodriguez 09.09.2017 в 02:55
source

2 answers

1

How about @ives. Good morning.

Well, it does not seem so convenient to have multiple cycles to perform the same task, as is the case, for example, of 'lowering' the positions in the array.

But well, starting from the base that the matrix will have the same number of rows and columns and besides the route that appears in the photo ( starting from the center outwards ), I will clarify the process with commented code, I hope to be descriptive enough in it so that you can analyze it without problems.

Look:

public void caracol( int tam ) {
    boolean abajo = true, izquierda = false, arriba = false; //Direcciones.
    boolean es_par = tam % 2 == 0; //Array2D par o impar?.
    int x = es_par ? tam / 2 - 1 : tam / 2;
    //Posicion inicial de 'x' sera la mitad MENOS 1 de las FILAS si el array es par, sino estara exactamente en la fila de la mitad.
    int y = tam / 2; //Posicion inicial de 'y' siempre en la columna del medio.
    int[][] mat = new int[ tam ][ tam ]; //Instancia del nuevo Array2D.

    for( int k = 1; k <= tam * tam; k++ ) { //Inicio de ciclo de 1 a total de posiciones en el array.
      mat[ x ][ y ] = k; //Contador almacenado en la coordenada.

      if( abajo ) { //Direccion hacia abajo.
        if( ( x - y > 0 && ! es_par ) || ( x - y >= 0 && es_par ) ) {
        //Condicional para diferenciar entre Array2D impar o par. [para impares se excluye la diagonal principal (x - y = 0) ].
          abajo = false; //Cambio de direccion y actualizacion de coordenada 'x' o 'y'.
          izquierda = true;
          y --;
        } else {
          x ++;
        }
      } else if( izquierda ) {// Direccion hacia la izquierda.
        if( x + y == mat.length - 1 ) {// Si se llega a la diagonal secundaria [x + y = tamano - 1], redireccionar.
          izquierda = false;// Cambio de direccion y actualizacion de coordenada 'x' o 'y'.
          arriba = true;
          x --;
        } else {
          y --;
        }
      } else if( arriba ) {// Direccion hacia arriba.
        if( ( x - y <= 0 && ! es_par ) || ( x - y < 0 && es_par ) ) {
        //Condicional para diferenciar entre Array2D impar o par. [para impares ahora se incluye la diagonal principal (x - y = 0) ].
          arriba = false;// Cambio de direccion y actualizacion de coordenada 'x' o 'y'.
          y ++;
        } else {
          x --;
        }
      } else if( x + y == mat.length - 1 ) {// [default] Direccion hacia la derecha hasta tocar la diagonal secundaria [x + y = tamano - 1].
        abajo = true;// Cambio de direccion y actualizacion de coordenada 'x' o 'y'.
        x ++;
      } else {
        y ++;
      }
    }// Fin de ciclo de 1 a total de posiciones en Array2D.

    // Impresion en consola.
    for( int i = 0; i < mat.length; i++ ) {
      System.out.println();
      for( int j = 0; j < mat.length; j++ ) {
        System.out.print( mat[ i ][ j ] + "\t" );
      }
    }
  }
  • Matrix of order 5:

  • Matrix of order 6:

    
answered by 09.09.2017 в 09:58
0

Here is a way to do it:

import java.util.*;

public class MatrizCaracol { 

private int[][] matriz; 
private int dimension; 
private int valores; 

public MatrizCaracol(int n) { 
    matriz = new int[n][n]; 
    dimension = n; 
    valores = n * n; 
    rellenar(); 
} 

private void rellenar() { 
    int fila, vuelta = 0, col, val = 1; 
    while (val <= valores) { 

        for (col = vuelta, fila = vuelta; val <= valores && col < dimension - 1 - vuelta; col++) { 
            matriz[fila][col] = val; 
            val++; 
        } 

        for (col = dimension - 1 - vuelta, fila = vuelta; val <= valores && fila < dimension - 1 - vuelta; fila++) { 
            matriz[fila][col] = val; 
            val++; 
        } 

        for (col = dimension - 1 - vuelta, fila = dimension - 1 - vuelta; val <= valores && col > vuelta; col--) { 
            matriz[fila][col] = val; 
            val++; 
        } 

        for (col = vuelta, fila = dimension - 1 - vuelta; val <= valores && fila > vuelta; fila--) { 
            matriz[fila][col] = val; 
            val++; 
        } 

        if (dimension % 2 != 0 && val == valores) { 
            col = fila = dimension / 2; 
            matriz[fila][col] = val; 
            val++; 
        } 
        vuelta++; 
    } 
} 

@Override 
public String toString() { 
    String out = ""; 

      for (int i = 0; i < dimension; i++) { 
      out+=(Arrays.toString(matriz[i])); 
      out+="\n"; 
    } 
    return out; 
} 

public static void main(String[] args){ 
    System.out.println(new MatrizCaracol(4)); 
} 

}

    
answered by 09.09.2017 в 08:56