Untitled
unknown
plain_text
a year ago
3.3 kB
5
Indexable
#include <iostream> using namespace std; int t, n, m; const int MN = 3000; int a[MN][MN]; struct Queue { int q[MN*MN]; int front, rear; Queue() { front = rear = -1; } void init() { front = rear = -1; } bool isEmpty() { return front == rear; } void push(int num) { q[++rear] = num; } int pop() { return q[++front]; } }; int dx[4] = {-1, 1, 0, 0}; int dy[4] = {0, 0, -1, 1}; Queue mq_x, mq_y; int dist[MN][MN]; bool is_valid(int x, int y) { return 0 <= x && x < n && 0 <= y && y < m; } int special_case(int x, int y) { int mc = 0; for (int i = 0; i < 4; ++i) { int nx = x + dx[i]; int ny = y + dy[i]; if (is_valid(nx, ny)) { if (dist[nx][ny] == -1) { return -1; } mc = max(mc, dist[nx][ny]); } } return mc; } void bfs(int sx, int sy) { mq_x.init(); mq_y.init(); mq_x.push(sx); mq_y.push(sy); dist[sx][sy] = 0; while (!mq_x.isEmpty()) { int x = mq_x.pop(); int y = mq_y.pop(); for (int i = 0; i < 4; ++i) { int nx = x + dx[i]; int ny = y + dy[i]; if (is_valid(nx, ny) && a[nx][ny] != 0 && dist[nx][ny] == -1) { if (a[nx][ny] == 2) { int sc = special_case(nx, ny); if (sc != -1) { mq_x.push(nx); mq_y.push(ny); dist[nx][ny] = 1 + dist[x][y]; } } else { mq_x.push(nx); mq_y.push(ny); dist[nx][ny] = 1 + dist[x][y]; } } } } } int main() { freopen("Text.txt", "r", stdin); cin >> t; for (int test_case = 1; test_case <= t; ++test_case) { cin >> n >> m; int sx, sy; cin >> sx >> sy; sx--; sy--; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { cin >> a[i][j]; dist[i][j] = -1; } } bfs(sx, sy); int cnt1 = -1, cnt2 = -1; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (a[i][j] != 0 && dist[i][j] == -1) { cnt1 = -1; break; } if (a[i][j] == 2 && dist[i][j] != -1) { cnt2 = dist[i][j]; } } } cout << "Case #" << test_case << '\n'; if (cnt1 != -1) { int im = 0, jm = 0; int is , js; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { cnt1 = max(cnt1, dist[i][j]); if (cnt1 < dist[i][j]) { cnt1 = dist[i][j]; im = i; jm = j; } if (a[i][j] == 2) { is = i; js = j; } } } if (dist[im][jm] > dist[is][js]) { cnt2++; } } cout << "Case #" << test_case << '\n'; cout << cnt2 << ' ' << cnt1 << '\n'; } return 0; }
Editor is loading...
Leave a Comment