Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <queue>
- using namespace std;
- int arr[130][130];
- int main() {
- for (int i = 0; i < 110; ++i)
- for (int j = 0; j < 110; ++j)
- arr[i][j] = -1;
- int n, m, ans = 1e6;
- cin >> n >> m;
- for (int i = 1; i <= n; ++i)
- for (int j = 1; j <= m; ++j) {
- cin >> arr[i][j];
- arr[i][j] *= -1;
- }
- queue<pair<int, pair<int, int> > > q;
- pair<int, pair<int, int> > k;
- k.first = 1;
- k.second.first = 1;
- k.second.second = 1;
- q.push(k);
- while(!q.empty()) {
- pair<int, pair<int, int> > v = q.front();
- q.pop();
- if (arr[v.first + 1][v.second.first] != -1 ) {
- int p = v.first + 1;
- while (arr[p][v.second.first] != -1) {
- if (arr[p][v.second.first] == -2 && ans > v.second.second)
- ans = v.second.second;
- ++p;
- }
- if (ans != 1e6)
- break;
- k.first = p - 1;
- k.second.first = v.second.first;
- k.second.second = v.second.second + 1;
- q.push(k);
- }
- if (arr[v.first - 1][v.second.first] != -1) {
- int p = v.first - 1;
- while (arr[p][v.second.first] != -1) {
- if (arr[p][v.second.first] == -2 && ans > v.second.second)
- ans = v.second.second;
- --p;
- }
- if (ans != 1e6)
- break;
- k.first = p + 1;
- k.second.first = v.second.first;
- k.second.second = v.second.second + 1;
- q.push(k);
- }
- if (arr[v.first][v.second.first + 1] != -1) {
- int p = v.second.first + 1;
- while (arr[v.first][p] != -1) {
- if (arr[v.first][p] == -2 && ans > v.second.second)
- ans = v.second.second;
- ++p;
- }
- if (ans != 1e6)
- break;
- k.first = v.first;
- k.second.first = p - 1;
- k.second.second = v.second.second + 1;
- q.push(k);
- }
- if (arr[v.first][v.second.first - 1] != -1) {
- int p = v.second.first - 1;
- while (arr[v.first][p] != -1) {
- if (arr[v.first][p] == -2 && ans > v.second.second)
- ans = v.second.second;
- --p;
- }
- if (ans != 1e6)
- break;
- k.first = v.first;
- k.second.first = p + 1;
- k.second.second = v.second.second + 1;
- q.push(k);
- }
- }
- cout << ans;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement