import java.util.*; import java.util.stream.Collectors; public class Varios { static int[] myArray = { 1, 2, 9, 2, 5, 3, 5, 1, 5 }; static int n = 3; private static int[][] fillMatriz ( int tamanoMatriz ) { int[][] matriz = new int[ tamanoMatriz ][ tamanoMatriz ]; int tamano = 0; for ( int indexA = 0; indexA < matriz.length; ++indexA ) { for ( int indexB = 0; indexB < matriz[ indexA ].length; ++indexB ) { matriz[ indexA ][ indexB ] = myArray[ tamano ]; // System.out.println ( matriz[ indexA ][ indexB ] ); tamano++; } } return matriz; } public static void main ( String[] args ) { int[][] matriz = fillMatriz ( n ); System.out.println ( encontarMinimoCosto ( matriz, matriz.length, matriz[ 0 ].length ) ); } private static String encontarMinimoCosto ( int[][] cost, int m, int n ) { List < Integer > listaColumna = new ArrayList <> ( ); List < Integer > listaNumeros = new ArrayList <> ( ); int primerIndice; // Recorrer primera columna for ( int i = 0; i < m; i++ ) { listaColumna.add ( cost[ i ][ 0 ] ); } int minimo = Collections.min ( listaColumna ); primerIndice = listaColumna.indexOf ( minimo ); listaNumeros.add ( minimo ); int indice = 0; // Recorrido a partir de la segunda columna for ( int i = 1; i < m; i++ ) { Map < Integer, Integer > mapa = new HashMap <> ( ); for ( int j = 0; j < n; j++ ) { // Validamos Segunda Columna contra la primera columna if ( i == 1 ) { if ( ( primerIndice - j ) == 0 ) { mapa.put ( j, cost[ j ][ i ] ); } else if ( Math.abs ( primerIndice - j ) == 1 ) { mapa.put ( j, cost[ j ][ i ] ); } } else { // Asignacion demas columnas if ( ( indice - j ) == 0 ) { mapa.put ( j, cost[ j ][ i ] ); } else if ( Math.abs ( indice - j ) == 1 ) { mapa.put ( j, cost[ j ][ i ] ); } } } // Obtenemos el indice a comparar y el minimo de la comparacion Map.Entry < Integer, Integer > min = Collections.min ( mapa.entrySet ( ), Map.Entry.comparingByValue ( ) ); minimo = min.getValue ( ); indice = min.getKey ( ); listaNumeros.add ( minimo ); } return listaNumeros.stream ( ) .map ( Object::toString ) .collect ( Collectors.joining ( " " ) ); } }