题解 | I 题 纯模拟 (抛砖引玉罢了

Hello,A+B!

https://ac.nowcoder.com/acm/contest/66846/A

//cpp 
#include<bits/stdc++.h>
using namespace std;
//设置偏移量 这样就可以在下面更方便的去寻找八个方向
int x[8] = {0, 0, 1, -1, 1, -1, 1, -1};
int y[8] = {1, -1, 0, 0, 1, 1, -1, -1};
char mp[505][505], new_mp[505][505];
//边界是500 预先开505 防止卡边界

int main() {
    int n, k;
    cin >> n >> k;

    for(int i = 0; i < n; i++) {
        for(int j = 0; j < n; j++) { 
            cin >> mp[i][j];
        }
    }
   // 因为我们需要记录下一次表的变化,但是不能改变当前的表 如果改变了会影响结果
   // 所以我们需要拷贝一个数组 new_mp
   
    memcpy(new_mp, mp, sizeof(mp));
    // 函数格式 target src size
    while(k--) {
       
        for(int i = 0; i < n; i++) {
            for(int j = 0; j < n; j++) {
                int num = 0;
                for(int m = 0; m < 8; m++) {
                    int x1 = i + x[m];
                    int y1 = j + y[m];
                    if(x1 >= 0 && x1 < n && y1 >= 0 && y1 < n) {
                        if(mp[x1][y1] == '1') {
                            num++;
                        }
                    }
                }
                if(mp[i][j] == '0' && num == 3) {
                    new_mp[i][j] = '1';
                } else if(mp[i][j] == '1' && num < 2) {
                    new_mp[i][j] = '0';
                } else if(mp[i][j] == '1' && (num == 2 || num == 3)) {
                    new_mp[i][j] = mp[i][j];
                } else if(mp[i][j] == '1' && num > 3) {
                    new_mp[i][j] = '0';
                }
            }
        }
         memcpy(mp, new_mp, sizeof(mp));
         //将处理好的数组放回去
    }

    for(int i = 0; i < n; i++) {
        for(int j = 0; j < n; j++) { 
            cout << mp[i][j] << ' ';
        }
        cout << endl;
    }
    
    return 0;
}

全部评论

相关推荐

一天代码十万三:这都不能算简历吧
点赞 评论 收藏
分享
Elastic90:公司不要求加班,但 又不允许你准点下班,经典又当又立
点赞 评论 收藏
分享
评论
2
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务