转载-华为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;
}