1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
| class Solution: def gobang(self, pieces: List[List[int]]) -> str: black = [defaultdict(set) for _ in range(4)] white = [defaultdict(set) for _ in range(4)] def add_pieces(x, y, c): p = black if c == 1: p = white p[0][x].add(y) p[1][y].add(x) p[2][x - y].add(y) p[3][x + y].add(y) def get_pos(x, y, k): if k == 0: return x, y elif k == 1: return y, x elif k == 2: return x + y, y else: return x - y, y
def find_pos(p, q, space): pos = defaultdict(set) for k in range(4): for idx, se in p[k].items(): vec = sorted(list(se)) for i in range(len(vec) - space + 1): start, end = vec[i], vec[i + space - 1] if end - start > 4: continue for s in range(end - 4, start + 1): arr = [v for v in range(s, s + 5) if v not in vec[i:i + space] and v not in q[k][idx]] if len(arr) == 2 and space == 3: x1, y1 = get_pos(idx, arr[0], k) x2, y2 = get_pos(idx, arr[1], k) pos[(x1, y1)].add((x2, y2)) pos[(x2, y2)].add((x1, y1)) if len(arr) == 1 and space == 4: x, y = get_pos(idx, arr[0], k) pos[(x, y)].add((x, y)) return pos
for x, y, c in pieces: add_pieces(x, y, c) b1_pos = find_pos(black, white, 4) if len(b1_pos) >= 1: return 'Black' w2_pos = find_pos(white, black, 4) if len(w2_pos) > 1: return 'White' if len(w2_pos) == 1: for x, y in w2_pos.keys(): add_pieces(x, y, 0) b3_pos = find_pos(black, white, 4) if len(b3_pos) > 1: return 'Black' else: b3_pos = find_pos(black, white, 3) for p, cnt in b3_pos.items(): if len(cnt) >= 2: print(p, cnt) return 'Black'
return 'None'
|