浙江大学1002题解-java

本文介绍了一个使用Java实现的棋盘放置问题解决方案。通过递归算法遍历棋盘的每一个位置,判断当前位置是否可以放置棋子,并计算最多能放置多少棋子。该程序接收输入并输出最大可放置棋子数。
import java.util.Scanner;

public class Main {
    private static int n;
    private static int max;
    private static Character[][] cs;
    
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        String[] strs;
        while(input.hasNext()) {
            n = input.nextInt();
            max = 0;
            if(n == 0) {
                break;
            }
            cs = new Character[n][n];
            strs = new String[n];
            input.nextLine();
            for(int i = 0; i < n; i++) {
                strs[i] = input.nextLine();
            }
            for(int i = 0; i < n; i++) {
                for(int j = 0; j < n; j++) {
                    cs[i][j] = strs[i].charAt(j);
                }
            }
            solve(0, 0);
            System.out.println(max);
        }
        input.close();
    }
    
    public static void solve(int x, int total) {    //total表示计数 到目前为止能摆放多少
        if(x == n*n) {
            if(total > max) {
                max = total;
                return;
            }
        } else {
            int r = x/n;
            int c = x%n;
            if(cs[r][c] == '.' && CanPut(r, c) == 1) {
                cs[r][c] = 'o';
                solve(x+1, total+1);
                cs[r][c] = '.';   //关键一步
            }
            solve(x+1, total);
        }
    }
    
    public static int CanPut(int r, int c) {
        for(int i = r; i >= 0; i--) {
            if(cs[i][c] == 'o') return 0;
            if(cs[i][c] == 'X') break;
        }
        for(int i = c; i >= 0; i--) {
            if(cs[r][i] == 'o') return 0;
            if(cs[r][i] == 'X') break;
        }
        return 1;
    }
    
}

 

转载于:https://www.cnblogs.com/NEU-2015/p/8099107.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值