2016-07-14 6 views
4

자바에 질문이 있습니다. 솔루션에 대해 얼마나 오랫동안 생각해도 문제를 해결할 수 없습니다 : 행렬이 있는데 가능한 가장 짧은 경로를 찾아야합니다. 매트의 [0] [0]부터 행렬의 오른쪽 아래에있는 숫자이며 그 숫자가 현재있는 사각형보다 큰 경우에만 인접한 사각형 (대각선 없음)으로 진행할 수 있습니다.행렬에서 최단 경로를 찾는 방법

For example: 
    0 1 2 3 4 
0 { 5 13 2 5 2 
1 58 24 32 3 24 
2 2 7 33 1 7 
3 45 40 37 24 70 
4 47 34 12 25 2 
5 52 56 68 76 100} 

그래서 유효한 해결책은 다음과 같습니다 (0,0) -> (0,1) -> (1,1) -> (2,1) -> (2,2) -> (2,3) → (3,1) → (3,0) → (0,4) → (0,5) → (5,1) → (5,2) 5,3) -> (5,4)

그리고 메소드는 가능한 가장 짧은 경로이기 때문에 14를 리턴합니다.

재귀 적 방법 (루프 없음)을 사용해야합니다.

이것은 내가 지금까지 생각해 낸 것이지만 어느 것이 가장 짧은 것인지 알아내는 방법을 모르겠습니다.

Public static int shortestPath(int[][]mat) 
{ 
    int length=0; 
    int i=0; 
    int j=0; 
    shortestPath(mat, length, i, j); 
} 


Private static int shortestPath(int[][]math, int length, int i, int j) 
{ 
    if((i==mat.length)||(j==mat[i].length)) 
     return length; 
    if(shortestPath(mat, length, i+1, j) > shortestPath(mat, length, i, j)) 
     return length +1; 
    if(shortestPath(mat, length, i, j+1) > shortestPath(mat, length, i, j)) 
     return length +1; 
    if shortestPath(mat, length, i-1, j) > shortestPath(mat, length, i, j)) 
     return length +1; 
    if shortestPath(mat, length, i, j-1) > shortestPath(mat, length, i, j)) 
     return length +1; 
} 

나는 그것을 할 수있는 방법이 있는지 확실하지 않다, 그리고 인 경우 : (지금은 모든 가능한 방법을 반환과 함께 추가 것이기 때문에 어떻게 내가 가장 짧은 방법 인 알고 나는 생각한다). 또한 매트릭스의 오른쪽 하단에 도달하는 것에 대해 추가해야한다고 생각합니다.

코드가 너무 복잡해서는 안됩니다.

+0

왼쪽이나 위로 또는 아래로 오른쪽으로 이동할 수 있습니까? 재귀의 기본 케이스는 언제입니까? 언제 그만합니까? 당신이 '밑바닥이되는'두 가지 상황을 볼 수 있습니다. 재귀적인 사례는 무엇입니까? –

+0

오른쪽 및 아래로 만 이동하면 가능한 모든 솔루션의 길이가 동일 해집니다 (10). 절대 올라가거나 왼쪽으로 가려면 넘은 숫자가 10보다 커야합니다. – FredK

+0

예, 위, 아래, 오른쪽, 왼쪽으로 이동할 수 있습니다. 나는 행렬의 끝에 도달하거나 내가 오른쪽 하단에 도달 할 때 멈출 필요가있다. 재귀 사례는 무엇을 의미합니까? – Uranus

답변

1

메신저 다음 작은 값에가는 방법이 가장 짧은 경우 확실하지만, 어쨌든하지 :

public class Pathfinder { 

    private int[][] matrix; 
    private int matrixLenghtI; 
    private int matrixLenghtJ; 

    public Pathfinder(int[][] matrix, int matrixLenghtI, int matrixLenghtJ) { 
     this.matrix = matrix; 
     this.matrixLenghtI = matrixLenghtI; 
     this.matrixLenghtJ = matrixLenghtJ; 
    } 

    public static void main(String[] args) { 

     int matrixLenghtI = 6; 
     int matrixLenghtJ = 5; 

     int[][] matrix1 = { { 3, 13, 15, 28, 30 }, { 40, 51, 52, 29, 30 }, { 28, 10, 53, 54, 54 }, 
       { 53, 12, 55, 53, 60 }, { 70, 62, 56, 20, 80 }, { 80, 81, 90, 95, 100 } }; 

     int[][] matrix2 = { { 5, 13, 2, 5, 2 }, { 58, 24, 32, 3, 24 }, { 2, 7, 33, 1, 7 }, { 45, 40, 37, 24, 70 }, 
       { 47, 34, 12, 25, 2 }, { 52, 56, 68, 76, 100 } }; 

     Pathfinder finder1 = new Pathfinder(matrix1, matrixLenghtI, matrixLenghtJ); 
     finder1.run(); 

     Pathfinder finder2 = new Pathfinder(matrix2, matrixLenghtI, matrixLenghtJ); 
     finder2.run(); 
    } 

    private void run() { 
     int i = 0; 
     int j = 0; 

     System.out.print("(" + i + "," + j + ")"); 
     System.out.println("\nLength: " + find(i, j)); 
    } 

    private int find(int i, int j) { 
     int value = matrix[i][j]; 
     int[] next = { i, j }; 

     int smallestNeighbour = 101; 
     if (i > 0 && matrix[i - 1][j] > value) { 
      smallestNeighbour = matrix[i - 1][j]; 
      next[0] = i - 1; 
      next[1] = j; 
     } 
     if (j > 0 && matrix[i][j - 1] < smallestNeighbour && matrix[i][j - 1] > value) { 
      smallestNeighbour = matrix[i][j - 1]; 
      next[0] = i; 
      next[1] = j - 1; 
     } 
     if (i < matrixLenghtI - 1 && matrix[i + 1][j] < smallestNeighbour && matrix[i + 1][j] > value) { 
      smallestNeighbour = matrix[i + 1][j]; 
      next[0] = i + 1; 
      next[1] = j; 
     } 
     if (j < matrixLenghtJ - 1 && matrix[i][j + 1] < smallestNeighbour && matrix[i][j + 1] > value) { 
      smallestNeighbour = matrix[i][j + 1]; 
      next[0] = i; 
      next[1] = j + 1; 
     } 

     System.out.print("->(" + next[0] + "," + next[1] + ")"); 

     if (i == matrixLenghtI - 1 && j == matrixLenghtJ - 1) 
      return 1; 

     return find(next[0], next[1]) + 1; 
    } 
} 

출력 : 정말이 문제 같은

(0,0)->(0,1)->(0,2)->(0,3)->(1,3)->(1,4)->(2,4)->(3,4)->(4,4)->(5,4)->(5,4) 
Length: 10 
(0,0)->(0,1)->(1,1)->(1,2)->(2,2)->(3,2)->(3,1)->(3,0)->(4,0)->(5,0)->(5,1)->(5,2)->(5,3)->(5,4)->(5,4) 
Length: 14 
+0

제안 해 주셔서 감사합니다.하지만 제가 언급했듯이, 이것은 재귀 적 방법이어야합니다. – Uranus

1

. 불행히도 저는 몇 년 동안 Java에서 일하지 않았습니다. 따라서이 대답은 의사 Java이며 일부 구문을 수정해야합니다. 아마도 함수 매개 변수 중 일부는 참조가되어야하며 복사본이 아니어야합니다. 당신은 그것을 알아낼 것이다 (업데이트 : 나는 파이썬에서 테스트 된 버전을 아래에 추가했다).

// just a little thing to hold a set of coordinates 
class Position 
{ 
    // not bothering with private/getters 
    public int x ; 
    public int y ; 
    public constructor (int x, int y) 
    { 
     this.x = x ; 
     this.y = y ; 
    } 
} 

class PathFinder 
{ 
    public void main (void) 
    { 
     // create a path with just the start position 
     start = new Position(0, 0) ; 
     path = new Vector() ; 
     path.add(start) ; 
     // create an empty path to contain the final shortest path 
     finalPath = new Vector() ; 
     findPath(path, finalPath) ; 
     print ("Shortest Path: ") ; 
     showPath (finalPath) ; 
    } 

    private void showPath (Vector path) { 
     // print out each position in the path 
     iter = path.iterator() ; 
     while (pos = iter.next()) { 
      print ("(%, %) ", pos.x, pos.y); 
     } 
     // print out the length of the path 
     print (" Length: %\n", path.size()) ; 
    } 

    // recursive function to find shortest path 
    private void findPath (Vector path, Vector finalPath) 
    { 
     // always display the current path (it should never be the same path twice) 
     showPath(path) ; 

     // where are we now? 
     here = path.lastElement() ; 

     // does the current path find the exit (position 4,5)? 
     if (here.x == 4 && here.y == 5) { 
      if (finalPath.size() == 0) { 
       //finalPath is empty, put the current path in finalPath 
       finalPath = path ; 
      } else { 
       // some other path found the exit already. Which path is shorter? 
       if (finalPath.size() > path.size()) { 
        finalPath = path ; 
       } 
      } 
      // either way, we're at the exit and this path goes no further 
      return ; 
     } 

     // path is not at exit; grope in all directions 
     // note the code duplication in this section is unavoidable 
     // because it may be necessary to start new paths in three 
     // directions from any given position 
     // If no new paths are available from the current position, 
     // no new calls to findPath() will happen and 
     // the recursion will collapse. 

     if (here.x > 0 && matrix[here.x-1][here.y] > matrix[here.x][here.y]) { 
      // we can move left 
      newPos = new Position(here.x-1, here.y) ; 
      newPath = path ; 
      newPath.add (newPos) ; 
      findPath(newPath, finalPath) ; 
     } 

     if (here.x < 4 && matrix[here.x+1][here.y] > matrix[here.x][here.y]) { 
      // we can move right 
      newPos = new Position(here.x+1, here.y) ; 
      newPath = path ; 
      newPath.add (newPos) ; 
      findPath(newPath, finalPath) ; 
     } 

     if (here.y > 0 && matrix[here.x][here.y-1] > matrix[here.x][here.y]) { 
      // we can move up 
      newPos = new Position(here.x, here.y-1) ; 
      newPath = path ; 
      newPath.add (newPos) ; 
      findPath(newPath, finalPath) ; 
     } 

     if (here.y < 5 && matrix[here.x][here.y+1] > matrix[here.x][here.y]) { 
      // we can move down 
      newPos = new Position(here.x, here.y+1) ; 
      newPath = path ; 
      newPath.add (newPos) ; 
      findPath(newPath, finalPath) ; 
     } 
    } 
} 

다음은 파이썬에서 동일한 알고리즘을 테스트 한 버전입니다. (나는 x, y을 좌표로 사용하는 것이 오도 된 것임을 알았습니다. x은 실제로 "수직"이고 y은 "수평 적"인 배열로 배열되어 있습니다. 나는 4 개의 출구와 한 쌍의 행렬을 설정했습니다 막 다른 골목으로.)

import copy, sys 

matrix = [ 
     [5, 13, 17, 58, 2], 
     [17, 24, 32, 3, 24], 
     [23, 7, 33, 1, 7], 
     [45, 40, 37, 38, 70], 
     [47, 34, 12, 25, 2], 
     [52, 56, 68, 76, 100]] 

def showPath(path): 
    for position in path: 
     sys.stdout.write("(" + str(position[0]) + ", " + str(position[1]) + "), ") 
    sys.stdout.write("\n\n") 
    sys.stdout.flush() 

def findPath(path): 
    #showPath(path) 
    global finalPath 
    x = path[-1][0] 
    y = path[-1][1] 
    if x == 5 and y == 4: 
     showPath(path) 
     if len(finalPath) == 0 or len(finalPath) > len (path): 
      finalPath[:] = copy.deepcopy(path) 
     return 
    if x > 0 and matrix[x-1][y] > matrix[x][y]: 
     # we can move up 
     newPath = copy.deepcopy(path) 
     newPath.append([x-1, y]) 
     findPath(newPath) 
    if x < 5 and matrix[x+1][y] > matrix[x][y]: 
     # we can move down 
     newPath = copy.deepcopy(path) 
     newPath.append([x+1, y]) 
     findPath(newPath) 
    if y > 0 and matrix[x][y-1] > matrix[x][y]: 
     # we can move left 
     newPath = copy.deepcopy(path) 
     newPath.append([x, y-1]) 
     findPath(newPath) 
    if y < 4 and matrix[x][y+1] > matrix[x][y]: 
     # we can move right 
     newPath = copy.deepcopy(path) 
     newPath.append([x, y+1]) 
     findPath(newPath) 

path = [] 
path.append([0, 0]) 
finalPath = [] 
findPath(path) 
print "Shortest Path: " + str(len(finalPath)) + " steps.\n" 
showPath(finalPath) 

당신이 findPath()의 첫 showPath() 전화 주석을 제거하면 모든 단계를 확인하고 막 다른 골목 포기받을 위치를 확인할 수 있습니다. 당신은 모든 가능성에 나무를 구축하고 짧은 다음 걸릴 수 있습니다 여기에

(0, 0), (1, 0), (2, 0), (3, 0), (4, 0), (5, 0), (5, 1), (5, 2), (5, 3), (5, 4), 
(0, 0), (1, 0), (1, 1), (1, 2), (2, 2), (3, 2), (3, 1), (3, 0), (4, 0), (5, 0), (5, 1), (5, 2), (5, 3), (5, 4), 
(0, 0), (0, 1), (1, 1), (1, 2), (2, 2), (3, 2), (3, 1), (3, 0), (4, 0), (5, 0), (5, 1), (5, 2), (5, 3), (5, 4), 
(0, 0), (0, 1), (0, 2), (1, 2), (2, 2), (3, 2), (3, 1), (3, 0), (4, 0), (5, 0), (5, 1), (5, 2), (5, 3), (5, 4), 
Shortest Path: 10 steps. 
(0, 0), (1, 0), (2, 0), (3, 0), (4, 0), (5, 0), (5, 1), (5, 2), (5, 3), (5, 4), 
0

: 당신은 출구에 도달 경로를 표시하는 경우처럼, 출력이 보인다. 이 결과를 추적하는 내부 루프입니다,하지만 당신은

import java.util.ArrayList; 
import java.util.Collections; 
import java.util.Comparator; 
import java.util.Map; 
import java.util.Map.Entry; 
import java.util.TreeMap; 

public class BetterPathfinder { 

    public class Comperator implements Comparator<Path> { 

     @Override 
     public int compare(Path o1, Path o2) { 
      return o1.getValue().compareTo(o2.getValue()); 
     } 
    } 

    public class Path { 

     private Integer lenght; 
     TreeMap<Integer, String> trace = new TreeMap<>(); 

     public Path(int lenght) { 
      this.lenght = lenght; 
     } 

     public Path(Path find, int i, int j) { 
      this.lenght = find.getValue() + 1; 
      this.trace.putAll(find.getTrace()); 

      this.trace.put(lenght, "(" + i + "," + j + ")"); 
     } 

     private Map<Integer, String> getTrace() { 
      return trace; 
     } 

     public Integer getValue() { 
      return lenght; 
     } 

     @Override 
     public String toString() { 
      String res = "end"; 
      for (Entry<Integer, String> is : trace.entrySet()) { 
       res = is.getValue() + "->" + res; 
      } 
      return res; 
     } 

    } 

    private int[][] matrix; 
    private int matrixLenghtI; 
    private int matrixLenghtJ; 

    public BetterPathfinder(int[][] matrix, int matrixLenghtI, int matrixLenghtJ) { 

     this.matrix = matrix; 
     this.matrixLenghtI = matrixLenghtI; 
     this.matrixLenghtJ = matrixLenghtJ; 

    } 

    public static void main(String[] args) { 

     int matrixLenghtI = 6; 
     int matrixLenghtJ = 5; 

     int[][] matrix1 = { { 3, 13, 15, 28, 30 }, { 40, 51, 52, 29, 30 }, { 28, 10, 53, 54, 54 }, 
       { 53, 12, 55, 53, 60 }, { 70, 62, 56, 20, 80 }, { 80, 81, 90, 95, 100 } }; 

     int[][] matrix2 = { { 5, 13, 2, 5, 2 }, { 58, 24, 32, 3, 24 }, { 2, 7, 33, 1, 7 }, { 45, 40, 37, 24, 70 }, 
       { 47, 34, 12, 25, 2 }, { 52, 56, 68, 76, 100 } }; 

     BetterPathfinder finder1 = new BetterPathfinder(matrix1, matrixLenghtI, matrixLenghtJ); 
     finder1.run(); 

     BetterPathfinder finder2 = new BetterPathfinder(matrix2, matrixLenghtI, matrixLenghtJ); 
     finder2.run(); 
    } 

    private void run() { 
     int i = 0; 
     int j = 0; 

     System.out.println(new Path(find(i, j), i, j)); 
    } 

    private Path find(int i, int j) { 
     int value = matrix[i][j]; 
     int[] next = { i, j }; 

     ArrayList<Path> test = new ArrayList<>(); 

     if (i == matrixLenghtI - 1 && j == matrixLenghtJ - 1) 
      return new Path(1); 

     if (i > 0 && matrix[i - 1][j] > value) { 
      next[0] = i - 1; 
      next[1] = j; 

      test.add(new Path(find(next[0], next[1]), next[0], next[1])); 
     } 
     if (j > 0 && matrix[i][j - 1] > value) { 
      next[0] = i; 
      next[1] = j - 1; 
      test.add(new Path(find(next[0], next[1]), next[0], next[1])); 
     } 
     if (i < matrixLenghtI - 1 && matrix[i + 1][j] > value) { 
      next[0] = i + 1; 
      next[1] = j; 
      test.add(new Path(find(next[0], next[1]), next[0], next[1])); 
     } 
     if (j < matrixLenghtJ - 1 && matrix[i][j + 1] > value) { 
      next[0] = i; 
      next[1] = j + 1; 
      test.add(new Path(find(next[0], next[1]), next[0], next[1])); 
     } 

     if (test.isEmpty()) { 
      return new Path(100); 
     } 

     return Collections.min(test, new Comperator()); 
    } 
} 

결과 ... 못생긴 IFS와 것을 주변에 얻을 수 있습니다 : 당신은 재귀 전략을 원하는

(0,0)->(1,0)->(1,1)->(1,2)->(2,2)->(3,2)->(4,2)->(5,2)->(5,3)->(5,4)->end 
(0,0)->(0,1)->(1,1)->(1,2)->(2,2)->(3,2)->(3,1)->(3,0)->(4,0)->(5,0)->(5,1)->(5,2)->(5,3)->(5,4)->end 
0

.꽤 쉽지만 비용이 많이 드는 방법은 단순히 보드를 범람시키는 것입니다. "가능한 모든 경로를 시도하고 거리를 계산하십시오"과 같은 것입니다.

자갈을 움직이는 것을 상상해 재귀 적으로 할 수 있습니다.

public int shortestPath(Point src, Point dest) { 
    if (src.equals(dest)) { 
      return 0; 
    } 

    // You need to do some bound checks here 
    int left = shortestPath(new Point(src.x - 1, src.y), dest); 
    int right = shortestPath(new Point(src.x + 1, src.y), dest); 
    int up = shortestPath(new Point(src.x, src.y + 1), dest); 
    int down = shortestPath(new Point(src.x, src.y - 1), dest); 

    // Decide for the direction that has the shortest path 
    return min(left, right, up, down) + 1; 
} 

솔루션이 나타내는 경로에 관심이있는 경우 만드는 동안 경로를 추적 할 수 있습니다. 이를 위해서는 단순히 min 방향으로 저장해야합니다.

전 컴퓨터 과학 연구에서 비슷한 작업을 해결해야했습니다. 우리는 의 chess board에 주어진 최소 이동량을 주어진 destination에 도달하기위한 필요량으로 계산해야했습니다. 어쩌면이 또한 도움 : http://pastebin.com/0xwMcQgj

0

위치 클래스 :

/** 
* Represents a position in the matrix. 
*/ 
public class Position { 

    final private int x; 
    final private int y; 

    public Position(int x, int y) { 
     this.x = x; 
     this.y = y; 
    } 

    public int getX() { 
     return x; 
    } 

    public int getY() { 
     return y; 
    } 

    @Override 
    public String toString() { 
     return "(" + x + ", " + y + ')'; 
    } 

    @Override 
    public boolean equals(Object o) { 
     if (this == o) return true; 
     if (o == null || getClass() != o.getClass()) return false; 

     Position position = (Position) o; 

     if (x != position.x) return false; 
     return y == position.y; 

    } 

    @Override 
    public int hashCode() { 
     int result = x; 
     result = 31 * result + y; 
     return result; 
    } 
} 

보드 클래스 :

/** 
* A board represents all of the locations in the matrix. It provides a simple interface to getting 
* the value in a position, and tracking the height and width of the matrix. 
*/ 
public class Board { 
    final int [][] board; 

    public Board(int[][] board) { 
     this.board = board; 
    } 

    final int positionValue(Position position) { 
     return this.board[position.getY()][position.getX()]; 
    } 

    final int getWidth() { 
     return board[0].length; 
    } 

    final int getHeight() { 
     return board.length; 
    } 
} 

패스 파인더 클래스 :

import java.util.ArrayList; 
import java.util.List; 

/** 
* Find the shortest path from a starting point to ending point in a matrix, assuming you can 
* only move to a position with a greater value than your current position. 
*/ 
public class PathFinder { 

    final private Board board; 
    final private Position start; 
    final private Position end; 


    public PathFinder(Board board, int startX, int startY, int endX, int endY) { 
     this.board = board; 
     this.start = new Position(startX, startY); 
     this.end = new Position(endX, endY); 
    } 

    /** 
    * Gets the shortest path from the start to end positions. This method 
    * takes all of the paths, then determines which one is shortest and returns that. 
    * 
    * @return the shortest path from the start to end positions. 
    */ 
    public List<Position> shortestPath() { 

     List<List<Position>> allPaths = this.getAllPaths(); 

     System.out.println("Paths found: " + allPaths.size()); 
     List<Position> shortestPath = null; 

     for (List<Position> path : allPaths) { 
      if (shortestPath == null) { 
       shortestPath = path; 
      } 
      else if (shortestPath.size() > path.size()) { 
       shortestPath = path; 
      } 
     } 

     return shortestPath; 
    } 

    /** 
    * Convenience method for starting the getAllPaths process. 
    * 
    * @return all of the paths from the start to end positions 
    */ 
    private List<List<Position>> getAllPaths() { 
     List<List<Position>> paths = new ArrayList<List<Position>>(); 
     return this.getAllPaths(paths, new ArrayList<Position>(), start); 
    } 

    /** 
    * Gets all of the paths from the start to end position. This is done recursively by visiting every 
    * position, while following the rules that you can only move to a position with a value greater 
    * than the position you're currently on. When reaching the end position, the path is added to 
    * the list of all found paths, which is returned. 
    * 
    * @param paths the current list of all found paths. 
    * @param path the current path 
    * @param position the current position 
    * @return all paths from the start to end positions 
    */ 
    private List<List<Position>> getAllPaths(List<List<Position>> paths, List<Position> path, Position position) { 
     path.add(position); 
     if (position.equals(end)) { 
      paths.add(path); 
      return paths; 
     } 

     //x+ 
     if (position.getX() + 1 < board.getWidth()) { 
      Position xp = new Position(position.getX() + 1, position.getY()); 
      if (board.positionValue(position) < board.positionValue(xp)) { 
       getAllPaths(paths, new ArrayList<Position>(path), xp); 
      } 
     } 
     //x- 
     if (position.getX() - 1 >= 0) { 
      Position xm = new Position(position.getX() - 1, position.getY()); 
      if (board.positionValue(position) < board.positionValue(xm)) { 
       getAllPaths(paths, new ArrayList<Position>(path), xm); 
      } 
     } 
     //y+ 
     if (position.getY() + 1 < board.getHeight()) { 
      Position yp = new Position(position.getX(), position.getY() + 1); 
      if (board.positionValue(position) < board.positionValue(yp)) { 
       getAllPaths(paths, new ArrayList<Position>(path), yp); 
      } 
     } 
     //y- 
     if (position.getY() - 1 >= 0) { 
      Position ym = new Position(position.getX(), position.getY() - 1); 
      if (board.positionValue(position) < board.positionValue(ym)) { 
       getAllPaths(paths, new ArrayList<Position>(path), ym); 
      } 
     } 

     return paths; 
    } 

    /** 
    * Run the example then print the results. 
    * 
    * @param args na 
    */ 
    public static void main(String[] args) { 
     int [][] array = {{5, 13, 2, 5, 2}, 
          {14, 24, 32, 3, 24}, 
          {15, 7, 33, 1, 7}, 
          {45, 40, 37, 24, 70}, 
          {47, 34, 12, 25, 2}, 
          {52, 56, 68, 76, 100} 
     }; 

     final Board board = new Board(array); 
     final Position end = new Position(board.getWidth()-1, board.getHeight() - 1); 
     final PathFinder pathFinder = new PathFinder(board, 0, 0, board.getWidth()-1, board.getHeight()-1); 

     final List<Position> path = pathFinder.shortestPath(); 

     System.out.println("Shortest Path: "); 
     for (Position position : path) { 
      if (!position.equals(end)) { 
       System.out.print(position + " -> "); 
      } 
      else { 
       System.out.println(position); 
      } 
     } 
     System.out.println(); 
    } 
} 
0
public class shortestPath{ 
public static int shortestPath(int[][] mat){ 
    if(mat == null || mat.length == 0 || mat[0].length == 0) 
     return 0; 
    else { 
     int n = shortestPath(mat, 0, 0, 0); 
     return (n == mat.length*mat.length+1) ? 0 : n; 
    } 
} 

private static int shortestPath(int[][]mat, int row, int col,int prev){ 

    if (!valid(mat,row,col) || !(mat[row][col] > prev)){ 
     return mat.length*mat.length+1; 
    } else if(row == mat.length - 1 && col == mat[row].length - 1) { 
     return 1; 
    } else { 
     return minimum(shortestPath(mat,row-1,col, mat[row][col]), 
      shortestPath(mat,row+1,col, mat[row][col]), 
      shortestPath(mat,row,col-1, mat[row][col]), 
      shortestPath(mat,row,col+1, mat[row][col])) + 1; 
    } 
} 

private static boolean valid(int[][]mat,int row, int col){ 
    if(row < 0 || col < 0 || col > mat[0].length-1 || row > mat.length-1) 
     return false; 
    else 
     return true; 
} 

private static int minimum(int x, int y, int t, int z){ 
    int min1 = (x > y)? y : x; 
    int min2 = (t > z)? z : t; 

    return (min1 > min2)? min2 : min1; 
} 

public static void main(String[] args){ 

    int maze[][] = { 
      { 3, 13, 15, 28, 30}, 
      { 40, 51, 52, 29, 30}, 
      { 28, 10, 53, 54, 53}, 
      { 53, 12, 55, 53, 60}, 
      { 70, 62, 56, 20, 80}, 
      { 81, 81, 90, 95, 100}}; 

    System.out.println(shortestPath(maze)); 
} 

}

관련 문제