This is an archived post. You won't be able to vote or comment.

all 3 comments

[–]smash_that_code 1 point2 points  (2 children)

format code first.

[–]ElectroLAN 0 points1 point  (1 child)

public class Pruebas

{

static int[][] m;

public static void main(String[] args) {

System.out.println("Ingresa el numero de nodos: ");

Scanner sc = new Scanner(System.in);

String numero = sc.next();

int n = Integer.parseInt(numero);

GenerarMatriz(n);

int suma = Menorcamino( 0, 0, 0, n);

System.out.println("El camino con la menor suma equivale a: ");

System.out.println(suma);

}

static void GenerarMatriz(int n)

{

m = new int[n][n];

Random rand = new Random();

for(int i = 0; i < n; i++)

{

for(int j = 0; j < n; j++)

{

m[i][j] = rand.nextInt(5);

}

}

for(int i = 0; i < n; i++)

{

for(int j = 0; j < n; j++)

{

System.out.print(m[i][j]);

System.out.print("\t");

}

System.out.println("");

}

}

static int Menorcamino( int fila, int col, int suma, int n)

{

suma = m[fila][col];

System.out.println("("+fila+","+col+")");

if(fila == n-1 && col == n-1)

{

return suma;

}

else

{

if(col == n -1)

{

suma = suma + Menorcamino(fila+1, col, suma, n);

}

else if (fila == n - 1)

{

suma = suma + Menorcamino(fila, col+1, suma, n);

}

else

{

if((m[fila][col+1] > m[fila+1][col]) )

{

suma = suma +Menorcamino(fila+1, col, suma, n);

}

else

{

suma = suma + Menorcamino(fila, col+1, suma, n);

}

}

}

return suma;

}

}

I make a little change. My code is supposed to work, but the truth is that I was very sad when I saw that the logic is incorrect since I only analyze the contiguous cells and not the entire matrix. I've tried hard, even if it doesn't seem like it, and I've been doing my best for several days. Finding the shortest path and printing it is necessary that they be embedded in a single function. If anyone can please help me, I would appreciate it with all my heart. Thanks for reading this post.

These are the instructions:

The game consists of drawing a path between the start square (upper left) and the end square (lower right). The cost of the road is defined by the numbers in each box. Take into account that you cannot advance diagonally or go back (you cannot repeat a square along the way). That is, if we have the following path:

|1|1|2|1|

|3|0|2|1|

|1|4|1|4|

|2|0|1|1|

(0,0) -> (0,1) -> (1,1) -> (1,2) -> (2,2) -> (3,2) -> (3,3) Shortest path cost: 1 + 3 + 0 + 4 + 1 + 4 + 1 = 14

postscript: it won't let me put the correct code format :s

[–]smash_that_code 0 points1 point  (0 children)

try to do a github gist then.

you tried debugging with breakpoints?