Shopee的办公室

题目:shopee的办公室非常大,小虾同学的位置坐落在右上角,而大门却在左下角,可以把所有位置抽象为一个网格(门口的坐标为0,0),小虾同学很聪明,每次只向上,或者向右走,因为这样最容易接近目的地,但是小虾同学不想让自己的boss们看到自己经常在他们面前出没,或者迟到被发现。他决定研究一下如果他不通过boss们的位置,他可以有多少种走法?

这道题典型的动态规划。

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

public class Main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc = new Scanner(System.in);
		String first = sc.nextLine();
		int x = Integer.parseInt(first.split(" ")[0]);
		int y = Integer.parseInt(first.split(" ")[1]);
		int n = Integer.parseInt(first.split(" ")[2]);
		//sc.nextLine();
		long[][] dp = new long[x+1][y+1];
		boolean[][] flag = new boolean[x+1][y+1];  //标记一下这个位置是否被阻塞了
		for(int i=0;i<n;i++) {
			String temp = sc.nextLine();
			flag[Integer.parseInt(temp.split(" ")[0])][Integer.parseInt(temp.split(" ")[1])]=true;
		}
		dp[0][0]=1;
		//确定边界条件
		for(int i=1;i<=x;i++) {
			if(flag[x-1][0]==true) {
				dp[i][0]=0;
			} else
				dp[i][0]=dp[i-1][0];
		}
		
		for(int j=1;j<=y;j++) {
			if(flag[0][j-1]==true) {
				dp[0][j]=0;
			} else
				dp[0][j]=dp[0][j-1];
		}
		
		for(int i=1;i<=x;i++) {
			for(int j=1;j<=y;j++) {
				if(flag[i-1][j]==true && flag[i][j-1]==true) {
					dp[i][j]=0;
				} else if(flag[i-1][j]==true) {
					dp[i][j]=dp[i][j-1];
				}
				else if(flag[i][j-1]==true) {
					dp[i][j]=dp[i-1][j];                
				} else {
					dp[i][j]=dp[i-1][j]+dp[i][j-1];
				}
			}
		}
		System.out.println(dp[x][y]);
	}
}

猜你喜欢

转载自blog.csdn.net/kidchildcsdn/article/details/114194702