动态规划练习题

题目内容

Given exact k steps, how many ways to move a point from start point to destination? Point can move for eight directions(horizontally, vertically, diagonally, anti-diagonally).

答案

public class Test {


    private static int[][] dir =  {{0,1},{1,0},{1,1},{1,-1},{0,-1},{-1,0},{-1,-1},{-1,1}};
    //DP
    /*
    @param dim, a tuple (width, height) of the dimensions of the board
    @param start, a tuple (x, y) of the king's starting coordinate
    @param target, a tuple (x, y) of the king's destination
     */
        public static int countPaths2(int[] dim, int[] start, int[] des, int steps){
            if(dim[0] == 0 || dim[1] == 0) return 0;
            int[][][] dp = new int[dim[0]*dim[1]][dim[1]*dim[0]][steps+1];
            for(int step = 0; step<=steps;step++){
                for(int i = 0; i< dim[0]*dim[1];i++){
                    for(int j = 0; j< dim[0]*dim[1];j++){
                        if(step == 0 && i == j){
                            dp[i][j][step] = 1;
                            continue;
                        }
                        for(int k =0; k< dir.length;k++){
                            int row = i / dim[0];
                            int col = i % dim[0];
                            if(row + dir[k][0] >= 0 && row + dir[k][0]< dim[0] && col + dir[k][1]>=0 && col + dir[k][1]< dim[1]){
                                int adj = (row + dir[k][0])*dim[0] + col + dir[k][1];
                                dp[i][j][step] += dp[adj][j][step-1];

                            }
                        }
                        
                    }
                }
            }
            int startPos = start[0]*dim[0] + start[1];
            int targetPos = des[0]*dim[0] + des[1];
            return dp[startPos][targetPos][steps];

        }


        public static void main(String[] args){
            int[] dim = {5,5};  // can just use to square;
            int[] start = {0,2};
            int[] end = {2,2};
            int steps = 2;
            System.out.println(countPaths2(dim, start,end, steps));
        }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值