求最短通路值

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));
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值