蓝桥杯 车的位置(DFS暴力搜索)

资源限制

内存限制: 256.0 M B 256.0 MB 256.0MB

C / C + + C/C++ C/C++ 时间限制: 1.0 s 1.0s 1.0s

J a v a Java Java 时间限制: 3.0 s 3.0s 3.0s

P y t h o n Python Python 时间限制: 5.0 s 5.0s 5.0s

问题描述

在一个 n ∗ n n*n nn 的棋盘中,每个格子中至多放置一个车,且要保证任何两个车都不能相互攻击,有多少中放法(车与车之间是没有差别的)

输入格式

包含一个正整数 n n n

输出格式

一个整数,表示放置车的方法数

样例输入

2

样例输出

7

数据规模与约定

n ≤ 8 n \le 8 n8

【样例解释】一个车都不放为1种,放置一个车有4种,放置2个车有2种。

解题思路

这道题是八皇后的阉割版,我们只需要用DFS暴力搜索出所有可能的放置情况即可。

代码如下:

import java.util.*;
import java.io.*;

public class Main{
    static int N = 10;
    static int n;
    static boolean[] row = new boolean[N];
    static boolean[] col = new boolean[N];
    static int ans = 0;
    
    static void dfs(int x, int y, int sum) {
        if (y == n) {
            y = 0;
            x += 1;
        }
        if (x == n) {
            if (sum == 0) {
                ans ++ ;
            }
            return;
        }
        dfs(x, y+1, sum);
        
        if (!row[x] && !col[y]) {
            row[x] = col[y] = true;
            dfs(x, y+1, sum-1);
            row[x] = col[y] = false;
        }
    }
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        PrintWriter pw = new PrintWriter(System.out);
        n = sc.nextInt();
        int res = 0;
        for (int i = 0; i <= n; i ++ ) {
            ans = 0;
            Arrays.fill(row, false);
            Arrays.fill(col, false);
            dfs(0, 0, i);
            res += ans;
        }
        pw.println(res);
        pw.close();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

取名真难www

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值