0
点赞
收藏
分享

微信扫一扫

蓝桥杯 - 玩具蛇

东言肆语 04-05 14:30 阅读 1

解题思路:

dfs

public class Main {
    static final int N = 4;
    static int[][] visited = new int[N][N];
    static int count;
    
    public static void main(String[] args) {
        for (int i = 0; i < N; i++) { //16种位置开始的可能
            for (int j = 0; j < N; j++) {
                dfs(i, j, 1);
            }
        }
        System.out.println(count);
    }
    
    public static void dfs(int x, int y, int step) {
        if (visited[x][y] == 0) {
            visited[x][y] = 1;
            dfs_two(x, y, step + 1);
            visited[x][y] = 0;
        }
    }
    
    public static void dfs_two(int x, int y, int step) {
        if (step == 17) {
            count++;
            return;
        }
        if (x > 0) dfs(x - 1, y, step); //上
        if (x + 1 < N) dfs(x + 1, y, step); //下
        if (y > 0) dfs(x, y - 1, step); //左
        if (y + 1 < N) dfs(x, y + 1, step); //右
    }
    
}
举报

相关推荐

0 条评论