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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include "osalib.h"
#include <algorithm>
#include <vector>
//#include <cstdio>
using namespace std;

int n, m, settlements, counted_settlements;
bool visited[1007][1007];
bool found;
pair<int, int> found_settlement;
vector<pair<int, int>> v;
char **board;

void NowaWyspa(int rows, int columns, char **Board) {
    board = Board;
    n = rows;
    m = columns;

    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < m; ++j) {
            if (board[i][j] == 'K') {
                ++settlements;
            }
        }
    }
}

pair<int, int> findSettlement() {
    for (int i = 0; i < n; ++i)
        for(int j = 0; j < m; ++j)
            if (board[i][j] == 'K')
                return make_pair(i, j);
    return make_pair(-1, -1);
}

//void printBoard() {
//    for (int i = 0; i < n; ++i) {
//        for (int j = 0; j < m; ++j)
//            printf("%c", board[i][j]);
//        printf("\n");
//    }
//    printf("\n");
//}

void dfs(int a, int b) {
    visited[a][b] = true;
    v.emplace_back(a, b);
//    char tmp = board[a][b];
//    board[a][b] = '*';
//    printBoard();
//    board[a][b] = tmp;

    if (board[a][b] == 'K')
        ++counted_settlements;
    if (counted_settlements == settlements)
        return;

    int x[] = {a + 1, a - 1, a, a};
    int y[] = {b, b, b + 1, b - 1};
    for (int i = 0; i < 4; ++i) {
        if (x[i] < n && x[i] >= 0 && y[i] < m && y[i] >= 0 \
            && board[x[i]][y[i]] != 'W' && !visited[x[i]][y[i]])
                dfs(x[i], y[i]);
    }
}

int NowaWarownia(int r, int c) {
    --r; --c;
    pair<int, int> s;
    if (found)
        s = found_settlement;
    else
        s = findSettlement();
    board[r][c] = 'W';
    if (settlements == 0)
        return 1;

    counted_settlements = 0;
    dfs(s.first, s.second);
    for (int i = 0; i < (int)v.size(); ++i)
        visited[v[i].first][v[i].second] = false;
    v.clear();

    if (counted_settlements == settlements)
        return 1;
    board[r][c] = '.';
    return 0;
}

void PrzeniesOsade(int r1, int c1, int r2, int c2) {
    --r1; --c1; --r2; --c2;
    board[r1][c1] = '.';
    board[r2][c2] = 'K';
    found = true;
    found_settlement = make_pair(r2, c2);
}