Take the underground palace treasure (deep search, memory type recursive)

Take the underground palace treasure

  1. King's X has a treasure trove underground palace . Is nxm lattice matrix. Each grid put a baby. Each baby close to the value of the label.

Underground palace entrance at the top left corner, exit at the bottom right corner.

Bob was taken to the inlet of the underground palace, the king asked him to walk to the right or down only.

Walked by a grid, the grid value if the baby is larger than the value of the hands of any baby Xiao Ming, Xiao Ming can pick it up (of course, you can not take).

When Bob went to the exit, if he happens to be in the hands of baby k pieces, then the baby will be given to Bob.

Please help Xiao Ming told, in a given situation, he has a number of different courses of action to get this k treasures.

  1. 3 integer input line , separated by spaces: nmk (1 <= n, m <= 50, 1 <= k <= 12)

Then there are n rows, each row having m integers Ci (0 <= Ci <= 12) representative of treasures of the squares of the value of

A required output integer representing the number of action programs just taking the k baby. This number may be large, its output modulo 1000000007.

  1. For example, Input :
    2 2 2
    . 1 2
    2. 1
    program should Output:
    2
    For another example, input:
    2. 3 2
    . 1 2. 3
    2. 1. 5
    program should Output:
    14

import java.util.Scanner;
public class Main {
	static int k;
	static int[][] arr;
	static int n;
	static int m;
	static int MOD=1000000007;
	public static void main(String[] args) {
		Scanner in=new Scanner(System.in);
		n=in.nextInt();
		m=in.nextInt();
		k=in.nextInt();     //2、可以取宝总数
		arr=new int[n][m];
		for(int i=0;i<n;i++) {
			for(int j=0;j<m;j++) {
				arr[i][j]=in.nextInt();
			}
		}
		for(int i=0;i<51;i++) {
			for(int j=0;j<51;j++) {
				for(int l=0;l<14;l++) {
					for(int o=0;o<14;o++) {
						cat[i][j][l][o]=-1;
					}
				}
			}
		}
		int res=dfs(0,0,-1,0);
		System.out.println(res);
	}
	static int[][][][] cat=new int[51][51][14][14];        //1、带有记忆的递归,有几个参数,建立几维数组,没有这一步只能的60分
	//1、max是取宝总数中最大价值,count是取宝总数
	public static int dfs(int x,int y,int max,int count) {   
		if(x==n||y==m||count>k) {
			return 0;
		}
		if(cat[x][y][max+1][count]!=-1) {
			return cat[x][y][max+1][count];
		}
		int ans=0;
		int cur=arr[x][y];      //cur是当前宝物的价值
		//1、到最后一个位置了,说明最多有一种取法,刚好差一个宝物,并且最后一个还符合条件,则是一种
		if(x==n-1&&y==m-1) {
			if(count==k||(count==k-1&&cur>max)){      
				return 1;
			}
			//1、没有满足要求,方案不计数,好比那些贪心的人,总想获得价值最高,结果什么也得不到
			return ans;
		}
		if(cur>max) {
			ans+=dfs(x+1,y,cur,count+1);      //1、向下走
			ans+=dfs(x,y+1,cur,count+1);
		}
		//2、当前价值小,不取直接走
		ans+=dfs(x+1,y,max,count);
		ans+=dfs(x,y+1,max,count);
		cat[x][y][max+1][count]=ans%MOD;
		return ans;
	}
}

Released eight original articles · won praise 1 · views 232

Guess you like

Origin blog.csdn.net/weixin_43946167/article/details/104730420