poj 1321 棋盘问题 回溯 Java

poj 1321 棋盘问题

import java.util.Arrays;
import java.util.Scanner;
/**
 * @author wangshaoyu
 */
public class POJ1321棋盘问题 {

    static int n;
    static int k;
    static int ans;
    static boolean[] rows; // 用于标记这一行是否已经放过棋子了
    static boolean[] cols; // 用于标记这一列是否已经放过棋子了
    static char[][] chess;

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (true) {
            n = in.nextInt();
            k = in.nextInt(); // k 个棋子
            if (n == -1 && k == -1) {
                break;
            }
            ans = 0;
            chess = new char[n][n];
            rows = new boolean[n];
            cols = new boolean[n];
            Arrays.fill(rows, false);
            Arrays.fill(cols, false);
            for (int i = 0; i < n; i++) {
                String str = in.next();
                chess[i] = str.toCharArray();
            }

            dfs(0, 0);
            System.out.println(ans);
        }
    }

    /**
     *
     * @param count 已经摆放好的棋子的数量
     */
    static void dfs (int count, int s) {
        // 如果棋子都放好了,就可以返回了
        if (count == k) {
            ans++;
            return;
        }
        // 每次都要从上一次放的下一行开始放
        for (int i = s; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (rows[i] == false && cols[j] == false && chess[i][j] == '#') {
                    rows[i] = true;
                    cols[j] = true;
                    // 需要从当前行的下一行开始放。
                    dfs(count + 1, i + 1);
                    rows[i] = false;
                    cols[j] = false;
                }
            }
        }
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值