蓝桥杯:填字母

题目:

  1. 轮到某人填的时候,只能在某个空格中填入L或O
  2. 谁先让字母组成了“LOL”的字样,谁获胜。
  3. 如果所有格子都填满了,仍无法组成LOL,则平局。

小明试验了几次都输了,他很惭愧,希望你能用计算机帮他解开这个谜。

本题的输入格式为:
第一行,数字n(n<10),表示下面有n个初始局面。
接下来,n行,每行一个串,表示开始的局面。
比如:“******”, 表示有6个空格。“L****”, 表示左边是一个字母L,它的右边是4个空格。

要求输出n个数字,表示对每个局面,如果小明先填,当K大师总是用最强着法的时候,小明的最好结果。
1 表示能赢
-1 表示必输
0 表示可以逼平

例如,
输入:
4
***
L**L
L**L***L
L*****L

则程序应该输出:
0
-1
1
1

public class FillLetters {
	static int f(char[] c) {
		String s = new String(c);
		if(s.contains("LOL")) return -1; //如果已包含LOL,输
		if(s.contains("*")==false) return 0;
		
		boolean ping = false;
		for(int i=0; i<c.length; i++) {
			if(c[i] == '*') {
				try {
					c[i] = 'L'; //尝试填 L
					switch (f(c)) { //对方回合
						case -1: return 1;
						case 0: ping = true;//如果return 0的话无法往下做尝试
					}
					c[i] = 'O';
					switch (f(c)) {
						case -1: return 1;
						case 0: ping = true;
					}
				}finally {
					c[i] = '*'; //回溯
				}
			}
		}
		if(ping) return 0;
		return -1;
	}
	
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = Integer.parseInt(sc.nextLine());
		String[] s = new String[n];
		for(int i=0; i<n; i++) {
			String a = sc.nextLine();
			s[i] = a;
		}
		for(String l:s) {
			char[] c = l.toCharArray();
			System.out.println(f(c));
		}
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_44260464/article/details/105546969