蓝桥杯之玩具蛇

图示
答案:552

public class Main {
    
    
    static long res = 0;
    static int cnt = 1;
    static int[][] dir = {
    
    {
    
    1, 0}, {
    
    0, 1}, {
    
    -1, 0}, {
    
    0, -1}};
    public static void main(String[] args) {
    
    
        for(int i = 0; i < 4; i++){
    
    
            for(int j = 0; j < 4; j++){
    
    
                boolean[][] used = new boolean[4][4];
                used[i][j] = true;
                dfs(used, i, j);
            }
        }
        System.out.println(res);
    }
    public static void dfs(boolean[][] used, int i, int j){
    
    
        if(cnt == 16){
    
    
            res++;
            return;
        }
        for(int k = 0; k < dir.length; k++){
    
    
            int x = i + dir[k][0];
            int y = j + dir[k][1];
            if(x < 0 || y < 0 || x >= 4 || y >= 4 || used[x][y]){
    
    
                continue;
            }
            cnt++;
            used[x][y] = true;
            dfs(used, x, y);
            cnt--;
            used[x][y] = false;
        }
    }
}

本题不能按以下的方式写。这样写的答案是:2208。因为将最后一个空填充完毕之后,此时会执行下面的 4 个dfs,但这 4 个dfs每个都会使结果加一,使得得到的答案是正确答案的 4 倍。

public class Error {
    
    
    static long res = 0;
    static int cnt = 0;
    public static void main(String[] args) {
    
    
        for(int i = 0; i < 4; i++){
    
    
            for(int j = 0; j < 4; j++){
    
    
                boolean[][] used = new boolean[4][4];
                dfs(used, i, j);
            }
        }
        System.out.println(res);
    }
    public static void dfs(boolean[][] used, int i, int j){
    
    
        if(cnt == 16){
    
    
            res++;
            return;
        }
        if(i < 0 || j < 0 || i >= 4 || j >= 4 || used[i][j]){
    
    
            return;
        }
        used[i][j] = true;
        cnt++;
        dfs(used, i + 1, j);
        dfs(used, i, j + 1);
        dfs(used, i - 1, j);
        dfs(used, i, j - 1);
        used[i][j] = false;
        cnt--;
    }
}

Guess you like

Origin blog.csdn.net/weixin_46497503/article/details/117039223