1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| package com.xinghuan;
import java.util.HashMap; import java.util.Map; import java.util.Scanner;
public class Main { static int[][] directions = new int[][]{{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; static HashMap<Integer, Integer> hashMap = new HashMap<>(); public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int[][] nums= new int[n][n];
for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { nums[i][j] = in.nextInt(); } } dfs(nums, n-1, n-1, 0);
int max_steps = Integer.MAX_VALUE; int choices = 0; for (Map.Entry<Integer, Integer> entry : hashMap.entrySet()) { int step = entry.getKey(); int choice = entry.getValue(); if (max_steps > step) { max_steps = step; choices = choice; } } System.out.println(max_steps); System.out.println(choices);
}
public static void dfs(int[][] nums, int i, int j, int cnt) { int n = nums.length; if (i == 0 && j == 0) { hashMap.put(cnt, hashMap.getOrDefault(cnt, 0) + 1); return ; } if (i >= n || i < 0 || j >= n || j < 0 || nums[i][j] == 0) return ; for (int d = 0; d < 4; d++) { nums[i][j] = 0; dfs(nums, i + directions[d][0], j + directions[d][1], cnt+1); nums[i][j] = 1; } } }
|