简体   繁体   中英

Search 2d Array

So im writing a java program which should find the shortest way from the entrance "2" to one of the numbers "3" . It can only walk on " " positions. "1" is walls.

11111121 
131    1 
1 1 1111 
1 1 13 1     
1 1 11 1 
1 1    1
1      1  
11111111

My starting idea is to find the entrance in the 2d array. This could be done like this:

Point entrance = new Point(0,0);
   for (int i = 0; i < N; i++) {
     for (int j = 0; j < N; j++){
        if(map[i][j] == 2){
           entrance.x =i;
           entrance.y =j;
        }
   }

I could also find the two "3" and save them in points. but im not sure how to return the rute to the closest "3" . I was considering like a joystick, where I save the what direction you go, like (UP, DOWN, LEFT, RIGHT). Then return the full list of moves from the entrance to the closests 3. Got any suggestion or ideas how I could implement this ?

What you have here is simply a non-cannonical representation of a graph. You have each cell being a vertex in the graph and you have an edge between two neighboring cells if and only if both of them are free.

Now that you look at the problem in this way, find the entrance like you do and than do a breadth first search to find the exit.

You need to make a counter that will increment every time the current position is " " (walk-able)

Notation " " = 0 in the matrix:

Point entrance = new Point(0,0);
for (int i = 0; i < N; i++) {
 for (int j = 0; j < N; j++){
    if(map[i][j] == 2){
       entrance.x =i;
       entrance.y =j;
    }
}

Point firstexit = new Point(0,0);
int steps = 0;
int i = entrance.x;
int j = entrance.y;
int lasti = 0;
int lastj = 0;
while(true){

    if(map[i][j] == 3){
       firstexit.x =i;
       firstexit.y =j;
       break ;
    }
    if(map[i][j] == 0){
       steps++;
    }

    // TO-DO : check if position exists
    if(map[i][j+1] == 0 && (lasti != i && lastj != j)){
       lastj = j;
       j++;
    }else if(map[i][j-1] == 0 && (lasti != i && lastj != j)){
       lastj = j;
       j--;
    }else if(map[i+1][j] == 0 && (lasti != i && lastj != j)){
       lasti = i;
       i++;
    }else if(map[i-1][j] == 0 && (lasti != i && lastj != j)){
       lasti = i;
       i--;
    }

}

I would try and create a graph with nodes and edges. Nodes are the junctions in the maze, and edges are the paths between junctions and entrance or exit objects. Each edge object has a 'weight'. Once you calculate the network from the double array, you can use some easy algorithm to work out the shortest route.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM