亲子游戏-od

这篇文章介绍了一个使用深度优先搜索(DFS)算法解决的编程问题,目标是在给定的二维数组中找到从特定位置到所有-2标记位置的最短路径,并记录遇到的最大婴儿(-3标记)数量。代码展示了如何遍历数组并更新全局最小步数和最大婴儿总数。
摘要由CSDN通过智能技术生成

转载-华为OD机试 - 亲子游戏(Java & JS & Python & C & C++)_亲子游戏od-CSDN博客

用例

4
-2 2 1 0
-1 1 3 1
-1 2 -3 9
-1 -1 5 -1

输出:6

解题思路

基础dfs遍历

public static int globalMinStepNum = Integer.MAX_VALUE;
	public static int globalMaxKity = 0;
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		while(sc.hasNext()) {
			globalMinStepNum = Integer.MAX_VALUE;
			globalMaxKity = 0;
			int num = sc.nextInt();
			int[][] nums = new int[num][num];
			int startRow = 0;
			int startCol = 0;
			for(int i=0;i< num;i++) {
				for(int j=0; j< num;j++) {
					nums[i][j] = sc.nextInt();
					if(nums[i][j] == -3) {
						startRow = i;
						startCol = j;
					}
				}
			}
			solution(nums, startRow, startCol, 0, 0);
			System.out.println(globalMaxKity);
		}
	}
	public static int solution(int[][] nums, int row, int col, int sum,int stepNum){
		if(nums[row][col] == -1) {// can't go on
			return 0;
		}
		if(nums[row][col] == -2) {// find baby
			if(globalMinStepNum > stepNum) {
				globalMinStepNum = stepNum;
				globalMaxKity = sum;
			}else if(globalMinStepNum == stepNum) {
				globalMaxKity = Math.max(globalMaxKity, sum);
			}
			return 0;
		}
		if(nums[row][col] != -1) {
			int tmp = nums[row][col];
			nums[row][col] = -1; // mark used
			if(tmp == -3) {// strat address, no kity
				tmp = 0;
			}
			if(row > 0) {
				solution(nums, row-1, col, sum+tmp,stepNum+1);
			}
			if(row < nums.length-1) {
				solution(nums, row+1, col, sum+tmp,stepNum+1);
			}
			if(col > 0) {
				solution(nums, row, col-1, sum+tmp,stepNum+1);
			}
			if(col < nums.length-1) {
				solution(nums, row, col+1, sum+tmp,stepNum+1);
			}
			nums[row][col] = tmp; // recover mark
			
		}
		return 0;
		
	}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值