Sie geben ein Raster (4x4 hier). Sie müssen die Gesamtzahl der eindeutigen Pfade von (0,0) bis (4,4) herausfinden. main() ruft dazu eine Funktion pathify auf. Es findet die möglichen "nächsten Schritte" und ruft sie erneut auf. Wenn (4,4) erreicht ist, noOfPaths ++; soll ausführen. Dies passiert nicht und ich kann das Problem nicht finden.Ich kann nicht meine statische Variable in Java ändern
import java.util.ArrayList;
public class NoOfPaths {
static int xRows = 4;
static int yColumns = 4;
static int noOfPaths = 0;
/*A robot is located in the upper-left corner of a 4×4 grid.
* The robot can move either up, down, left, or right,
* but cannot go to the same location twice.
* The robot is trying to reach the lower-right corner of the grid.
* Your task is to find out the number of unique ways to reach the destination.
**/
static ArrayList validNeighbours (int x,int y, ArrayList visited) {
ArrayList valid = new ArrayList();
if((x+1 <= xRows) && !visited.contains(((x+1)*10)+y)) {
valid.add(((x+1)*10)+y);
}
if((x-1 >= 0) && !visited.contains(((x-1)*10)+y)) {
valid.add(((x-1)*10)+y);
}
if((y+1 <= yColumns) && !visited.contains(x*10+y+1)) {
valid.add(x*10+y+1);
}
if((y-1 >= 0) && !visited.contains(x*10+y-1)) {
valid.add(x*10+y-1);
}
return valid;
}
static void pathify(int x,int y, ArrayList alreadyVisited) {
if(x == xRows && y == yColumns) {
noOfPaths++;
} else {
alreadyVisited.add(x*10+y);
ArrayList callAgain = new ArrayList();
callAgain = validNeighbours(x,y,alreadyVisited);
for (int t=0,temp; t<callAgain.size(); t++) {
temp=(int) callAgain.get(t);
pathify(temp/10, temp%10, alreadyVisited);
}
}
}
public static void main(String[] args) {
ArrayList alreadyVisited = new ArrayList();
pathify(0, 0, alreadyVisited);
System.out.println(noOfPaths);
}
}
eine kleine Bemerkung am Rande, wenn Sie Generika als 'Liste' verwenden müssen Sie nicht auf 'int' den ganzen Tag typisieren lange und Ihr Code mehr typsicher bekommen –
SomeJavaGuy
wird, dass der Geist in halten –
Sie nur eine Kopie des Arrays Modifizieren Listen Sie nicht die tatsächliche Arraylist auf. – eldo