How to make a Spiral-Snail Tour of a Matrix n * m (not square n * n)

0

Here I have this code to make a Caracol or Spiral Matrix, its path is from the "0,0" position to the middle of the matrix. However, I do not know how to do the algorithm so that it allows me to enter matrices n * m, that is to say, they are not square ... since in doing so it marks me error :(

package matrizespiral;

import java.util.Scanner;

/**
 * Matriz Cuadrada con recorrido en Caracol o Espiral
 * 
 * Tiene doble filo el exigir la dimension de la matriz por teclado, 
 * Buscamos poder permitir mostrar el resultado de una matriz n*m tambien.
 * Pero no se como T_T
 * @author HD
 */
public class MatrizCaracolHD {

    public static void main(String[] args) {

        //Creando matriz con valores que da el usuario
        Scanner sc = new Scanner(System.in);
        System.out.print("--- Dimesión de la Matriz ---\n");
        System.out.println("    Ingrese numero de filas: ");
        int fil = sc.nextInt();
        System.out.println("    Ingrese numero de columnas: ");
        int col = sc.nextInt();
        mostrarMatriz(crearMatrizc(fil, col, 1), fil, col);

    }//finmain

    /**
     * Genera Una Matriz Caracol.
     *
     * @param fil filas dimensión de la matriz cuadrada
     * @param col columnas de la matriz.. aun en proceso de que se pueda con n*col
     * @param matrizAux numero con cual se iniciara la matriz caracol
     * @return matriz de enteros con la matriz caracol ya generada.
     */
    public static int[][] crearMatrizc(int fil, int col, int matrizAux) {

        int[][] matrizc = new int[fil + 1][col + 1];

        for (int pos = 1; pos <= fil / 2; pos++) {
            for (int i = pos; i <= col - pos; i++) {
                matrizc[pos][i] = matrizAux;
                matrizAux++;
            }
            for (int i = pos; i <= col - pos; i++) {
                matrizc[i][col - pos + 1] = matrizAux;
                matrizAux++;
            }
            for (int i = col - pos + 1; i >= pos + 1; i--) {
                matrizc[col - pos + 1][i] = matrizAux;
                matrizAux++;
            }
            for (int i = col - pos + 1; i >= pos + 1; i--) {
                matrizc[i][pos] = matrizAux;
                matrizAux++;
            }
        }
        //si la columna es impar 
        if (col % 2 == 1) {
            matrizc[col / 2 + 1][col / 2 + 1] = matrizAux;
            System.out.println("\nMatriz cuadrada IMPAR de  "+fil+" x "+col+" = "+matrizAux+" elementos");
        }else{matrizAux--;System.out.println("\nMatriz cuadrada PAR de  "+fil+" x "+col+" = "+matrizAux+" elementos");}
        return matrizc;
    }//fincrear

    /**
     * Muestra una Matriz cualquiera usando las filas y columnas como parametro
     *
     * @param matrizc matriz int[][] por mostrar
     * @param f numero de filas de la matriz por mostrar
     * @param c numero de columnas de la matriz por mostrar
     */
    public static void mostrarMatriz(int[][] matrizc, int f, int c) {
        for (int i = 1; i <= f; i++) {
            for (int j = 1; j <= c; j++) {
                System.out.print(matrizc[i][j] + " \t");
            }
            System.out.println();
        }
    }//finmostrar
}//finclass
    
asked by HeckDan 22.10.2017 в 05:24
source

1 answer

1

Alternative solution for the Caracol Tour.

Debug this code and see how it works line by line ( because this contribution would be more valuable going beyond a copy / paste ); Now, opting for a few conditionals instead of the multiple cycles for that you raise ...

private static void mostrarMatriz( int columnas, int filas ) {
  boolean derecha = true, izquierda = false, abajo = false;
  int[][] matrizc = new int[ filas ][ columnas ];
  int x = 0, y = -1;

  for( int k = 1; k <= columnas * filas; k++ ) {
    if( izquierda ) {
      y --;
      if( y == -1 ) {
        y = 0; x --;
        izquierda = false;
      } else if( matrizc[ x ][ y ] != 0 ) {
        y ++; x --;
        izquierda = false;
      }
    } else if( derecha ) {
      y ++;
      if( y == columnas ) {
        y = columnas - 1; x ++;
        derecha = false;
        abajo = true;
      } else if( matrizc[ x ][ y ] != 0 ) {
        y --; x ++;
        derecha = false;
        abajo = true;
      }
    } else if( abajo ) {
      x ++;
      if( x == filas ) {
        x = filas - 1; y --;
        abajo = false;
        izquierda = true;
      } else if( matrizc[ x ][ y ] != 0 ) {
        y --; x --;
        abajo = false;
        izquierda = true;
      }
    } else {
      x --;
      if( x == -1 || matrizc[ x ][ y ] != 0 ) {
        x ++; y ++;
        derecha = true;
      }
    }

    matrizc[ x ][ y ] = k;
  }

  for( int i = 0; i < filas; i++ ) {
    for( int j = 0; j < columnas; j++ ) {
      System.out.print( matrizc[ i ][ j ] + "\t" );
    }
    System.out.println();
  }

  String info = filas == columnas ? "Matriz Cuadrada de " : "Matriz Rectangular de ";
  System.out.println( "[" + info + columnas + "*" + filas + " = " + columnas * filas + " elementos]" );
}

    
answered by 22.10.2017 в 09:41