题解 | 贪吃蛇游戏

贪吃蛇游戏

https://www.nowcoder.com/practice/ec61c899432f469bb8b3f96b44c23e79

#include <bits/stdc++.h>
using namespace std;
using ll = long long;

deque<pair<int, int>> snake;

bool moveSnake(int dir) {
    // TODO: 请实现移动逻辑
    auto head = snake.back();
    switch (dir) {
        case 1:
            head.second++;
            break;
        case 2:
            head.second--;
            break;
        case 3:
            head.first--;
            break;
        case 4:
            head.first++;
            break;
    }
    snake.push_back(head);
    snake.pop_front();
    for (int i = 0; i < snake.size() - 1; i++) {
        if (snake[i] == head) return true;
    }
    return false;
}

bool eatSnake(int dir) {
    // TODO: 请实现吃果子生长逻辑
    auto head = snake.back();
    switch (dir) {
        case 1:
            head.second++;
            break;
        case 2:
            head.second--;
            break;
        case 3:
            head.first--;
            break;
        case 4:
            head.first++;
            break;
    }
    snake.push_back(head);
    for (int i = 0; i < snake.size() - 1; i++) {
        if (snake[i] == head) return true;
    }
    return false;
}



int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n, q;
    cin >> n >> q;
    snake.clear();
    for (int i = 0; i < n; i++) {
        int x, y;
        cin >> x >> y;
        snake.emplace_back(x, y);
    }
    for (int i = 0; i < q; i++) {
        int op, dir;
        cin >> op >> dir;
        bool collision = (op == 1 ? moveSnake(dir) : eatSnake(dir));
        if (collision) {
            cout << -1 << '\n';
            return 0;
        } else {
            for (auto it = snake.rbegin(); it != snake.rend(); ++it) {
                cout << it->first << ' ' << it->second << '\n';
            }
        }
    }
    return 0;
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务