最大值路径

对此问题做一般化描述:
  有n阶方阵,从矩阵的左下角元素为起点,从行或列(水平或垂直)两个方向上移动,直到右上角。求出有多少条路径可以使得经过的元素累加值最大,最大值是多少。
输入格式
  共有n+1行。
  第一行整数n,表示矩阵的阶数,2<=n<=10。
  第二行起,每行n个整数,以空格分隔,共n行。。
输出格式
  一行,两个空格分隔的数,第一个表示最大值路径的条数,第二个表示最大值。
样例输入
5
4 5 4 5 6
2 6 5 4 6
2 6 6 5 2
4 5 2 2 5
5 2 5 6 4
样例输出
3 47

import java.util.ArrayList;
import java.util.Scanner;
public class 最大路径 {

	static int n;
	//用来存放矩阵的值
	static int[][] map ;
	//定义一个动态数组,用来存放每一次访问到右上角的最大路径
	static ArrayList<Integer> arr = new ArrayList<Integer>();
	//用来标记已经访问过的结点
	static int[][] maker ;
	//行走的方向,上和右
	static int[][] dir = {{-1,0},{0,1}};
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		n = sc.nextInt();
		map = new int[n+1][n+1];
		maker = new int[n+1][n+1];
		for(int i = 0;i<n;i++)
		{
			for(int j = 0;j<n;j++)
			{
				map[i][j] = sc.nextInt();
			}
		}
		int sum = map[n-1][0];
		dfs1(n-1,0,sum);
		int max1 = 0;
		//找到最大值
		for(int i = 0;i<arr.size();i++)
		{
			int temp = arr.get(i);
			if(temp>max1)
			{
				max1 = temp;
			}
		}
		int sum1 = 0;
		//计算最大路径的个数
		for(int i = 0;i<arr.size();i++)
		{
			int temp = arr.get(i);
			if(temp==max1)
			{
				sum1++;
			}
		}
		System.out.println(sum1+" "+max1);
	}
	//深搜
	private static void dfs1(int x, int y,int cnt) {
		int max = 0;
		//每次到达右上角就得到一种可能的走法
		if(x==0&&y==n-1)
		{
			if(cnt>max)
			{
				max = cnt;
				arr.add(max);//把每次走的路径和添加到动态数组中
				return;
			}										
		}
		for(int i= 0 ;i<2;i++)
		{
			int tx = x+dir[i][0];
			int ty = y+dir[i][1];
			if(!in(tx,ty))//判断是否越界
				continue;
			if(maker[tx][ty]==0)
			{
				maker[tx][ty]=1;
				//向新的结点探索,并累加每个结点的权值
				dfs1(tx, ty,cnt+map[tx][ty]);
				maker[tx][ty]=0;//回溯
			}
		}
		
	}
	
	private static boolean in(int tx, int ty) {
		return tx>=0&&tx>=0&&ty<n&&tx<n;
	}
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值