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
| #include <iostream> #include <queue> using namespace std; int n, m, rx, ry, bx, by, crx, cry, cbx, cby, cqc, cnt1, cnt2, v[12][12][12][12], dx[] = {0, 0, -1, 1}, dy[] = {-1, 1, 0, 0}, ans; char arr[12][12]; queue<int> x1, x2, y1, y2, qc; int main() { cin >> n >> m; for(int i = 0; i < n; i++) { scanf("%s", &arr[i]); for(int j = 0; j < m; j++) if(arr[i][j] == 'R') rx = j, ry = i; else if(arr[i][j] == 'B') bx = j, by = i; } x1.push(rx), x2.push(bx), y1.push(ry), y2.push(by), qc.push(0); v[rx][ry][bx][by] = 1; while(!x1.empty()) { rx = x1.front(); x1.pop(); ry = y1.front(); y1.pop(); bx = x2.front(); x2.pop(); by = y2.front(); y2.pop(); cqc = qc.front(); qc.pop(); if(cqc > 10) { cout << "-1"; return 0; } if(arr[ry][rx] == 'O') { cout << cqc; return 0; } for(int i = 0; i < 4; i++) { crx = rx; cry = ry; cbx = bx; cby = by; cnt1 = 0; cnt2 = 0; while(arr[cry + dy[i]][crx + dx[i]] != '#' && arr[cry][crx] != 'O') { crx += dx[i]; cry += dy[i]; cnt1++; } while(arr[cby + dy[i]][cbx + dx[i]] != '#' && arr[cby][cbx] != 'O') { cbx += dx[i]; cby += dy[i]; cnt2++; } if(crx == cbx && cry == cby) { if(arr[cby][cbx] == 'O') continue; if(cnt1 > cnt2) { crx -= dx[i]; cry -= dy[i]; } else { cbx -= dx[i]; cby -= dy[i]; } } if(v[crx][cry][cbx][cby]) continue; v[crx][cry][cbx][cby] = 1; x1.push(crx), x2.push(cbx), y1.push(cry), y2.push(cby), qc.push(cqc + 1); } } cout << "-1"; }
|