8th national competition java test question 5: letter filling game

Alphabet game


Xiao Ming is often addicted to playing LOL games. Once he wanted to challenge Master K. Unexpectedly, Master K said: "Let's play a game of filling in the blanks first. If you can't beat me, don't play LOL again." Master K drew a line of n grids on the paper and asked Xiao Ming and him to alternately fill in letters.
and:

  1. When it's someone's turn to fill in, you can only fill in L or O in a certain box.
  2. Whoever makes the letters form the word "LOL" first wins.
  3. If all the squares are filled and the LOL cannot be formed, it is a tie.

Xiaoming tried several times and failed. He was ashamed. I hope you can use the computer to help him solve this mystery.
The input format of this question is: the
first line, the number n (n<10), indicating that there are n initial positions below. Next, there are n rows, one string per row, indicating the starting position.

比如:“******”,  表示有6个空格。 “L****”,   表示左边是一个字母L,它的右边是4个空格。
要求输出n个数字,表示对每个局面,如果小明先填,当K大师总是用最强着法的时候,小明的最好结果。
1 表示能赢
-1 表示必输
0 表示可以逼平

For example,
enter:

4
***
L**L
L**L***L
L*****L

Then the program should output:
0
-1
1
1
Idea:
The problem is a game problem. We can use a dictionary to store the results we know before, in order to reduce the time complexity of deep search and reduce the running time of the program. The form of the game problem is basically that the previous frame is the condition for judging win or lose, and for is to traverse various moves, always making Xiaoming the best result. if s in d: is to judge whether the optimal solution is known before. But the Blue Bridge Cup can only pass 60 points.
program:

def me(w):
    global d
    s="".join(w)
    if s in d:
        return d[s]
    if s.count("LOL")>0:return -1
    if len(s)<3 or s.count("*")==0: return 0
    c=-1
    for i in range(0,len(w)):
        if w[i]=="*":
            try:
                w[i]="L"#试着填L
                c=max(c,-me(w))
                if c==1:
                    break
                else:
                    w[i]="O"#试着填O
                    c=max(c,-me(w))
                    if c==1:
                        break
            finally:
                w[i]="*"#回溯
    s="".join(w)
    d[s]=c
    return c
    
w=int(input())
w1=[input() for i in range(w)]
for i in w1:
    d={
    
    }
    print(me(list(i)))

Reprinting is prohibited. Only for self-study. No responsibility for program errors.

Guess you like

Origin blog.csdn.net/weixin_46640345/article/details/112848361