import java.util.LinkedList;
import java.util.Queue;
/**
* Created by lxw, liwei4939@126.com on 2017/11/3.
* 求最短通路值
* 广度优先搜索
*/
public class minPath {
public int minPathValue(int[][] m){
if(m == null || m.length == 0|| m[0].length ==0 ||
m[0][0] != 1 || m[m.length-1][m[0].length - 1] != 1){
return 0;
}
int res = 0;
int[][] map = new int[m.length][m[0].length];
map[0][0] = 1;
Queue<Integer> rQ = new LinkedList<Integer>();
Queue<Integer> cQ = new LinkedList<Integer>();
rQ.add(0);
cQ.add(0);
int r = 0;
int c = 0;
while (!rQ.isEmpty()){
r = rQ.poll();
c = cQ.poll();
if(r == m.length- 1 && c == m[0].length - 1){
return map[r][c];
}
walkTo(map[r][c], r - 1, c, m, map, rQ, cQ);
walkTo(map[r][c], r + 1, c, m, map, rQ, cQ);
walkTo(map[r][c], r, c - 1, m, map, rQ, cQ);
walkTo(map[r][c], r, c + 1, m, map, rQ, cQ);
}
return res;
}
public void walkTo(int pre, int toR, int toC, int[][] m,
int[][] map, Queue<Integer> rQ, Queue<Integer> cQ){
if(toR < 0 || toR == m.length || toC < 0 || toC == m[0].length ||
m[toR][toC] != 1 || map[toR][toC] != 0){
return;
}
map[toR][toC] = pre + 1;
rQ.add(toR);
cQ.add(toC);
}
public static void main(String[] args){
minPath tmp = new minPath();
int[][] matrix = {{1, 0, 1, 1, 1},{1, 0, 1, 0, 1},
{1, 1, 1, 0, 1},{0, 0, 0, 0, 1}};
System.out.println(tmp.minPathValue(matrix));
}
}
求最短通路值
最新推荐文章于 2023-10-26 16:51:08 发布