2011-12-03 71 views
0

问题是从起点到终点找到网格上的最短路径。网格是一个二维数组,填充0和1。 1是路径。我有一个方法来检查给定坐标的邻居,看它是否是一条路径。我遇到的问题是网格的边界。可以使用数组长度和列长度来检查右边界和底部边界。但是,我将如何检查以确保我不试图检查网格左侧或网格上方的点?java网格边界

这是我的方法

public static void neighbors(coordinate current, int[][] grid, Queue q) 
    { 
    int row = current.getRow(); 
    int col = current.getCol(); 

    if(grid[row-1][col] == 1) 
    { 
     if(grid[row][col] == -1) 
     { 
      grid[row-1][col] = grid[row][col] + 2; 
     } 

     else 
     { 
      grid[row-1][col] = grid[row][col] + 1; 
     } 

     coordinate x = new coordinate(row-1,col); 
     q.enqueue(x); 
    } 

    else if(grid[row+1][col] == 1) 
    { 
     if(grid[row][col] == -1) 
     { 
      grid[row+1][col] = grid[row][col] + 2; 
     } 

     else 
     { 
     grid[row+1][col] = grid[row][col] + 1; 
     } 

     coordinate x = new coordinate(row+1,col); 
     q.enqueue(x); 
    } 

    else if(grid[row][col-1] == 1) 
    { 
     if(grid[row][col] == -1) 
     { 
      grid[row][col-1] = grid[row][col] + 2; 
     } 

     else 
     { 
      grid[row][col-1] = grid[row][col] + 1; 
     } 

     coordinate x = new coordinate(row, col - 1); 
     q.enqueue(x); 

    } 

    else if(grid[row][col+1] == 1) 
    { 
     if(grid[row][col+1] == -1) 
     { 
      grid[row][col+1] = grid[row][col] + 1; 
     } 

     else 
     { 
      grid[row][col+1] = grid[row][col] + 1; 
     } 

     coordinate x = new coordinate(row, col + 1); 
     q.enqueue(x); 

    } 

    else 
    { 

    } 

    q.dequeue(); 


} 

回答

0

我认为最左边最上面和指标都在你的阵列0,所以只要确保索引1> = 0索引到相应的阵列之前。