1 条题解

  • 1
    @ 2024-10-13 19:01:31

    参考答案:

    #include <iostream>//普通版
    using namespace std;
    const int N = 1010;
    char a[N][N];
    int b[N][N];
    int main()
    {
        int n, m;
        cin >> n >> m;
        for (int i = 1; i <= n; ++i)
        {
            for (int j = 1; j <= m; ++j)
            {
                cin >> a[i][j];
            }
        }
        for (int i = 1; i <= n; ++i)
        {
            for (int j = 1; j <= m; ++j)
            {
                int sum = 0;
                if (a[i][j + 1] == '*') ++ sum;
                if (a[i][j - 1] == '*') ++ sum;
                if (a[i - 1][j] == '*') ++ sum;
                if (a[i + 1][j] == '*') ++ sum;
                if (a[i - 1][j - 1] == '*') ++ sum;
                if (a[i - 1][j + 1] == '*') ++ sum;
                if (a[i + 1][j - 1] == '*') ++ sum;
                if (a[i + 1][j + 1] == '*') ++ sum;
                b[i][j] = sum;
            }
        }
        for (int i = 1; i <= n; ++i)
        {
            for (int j = 1; j <= m; ++j)
            {
                if (a[i][j] != '*') printf("%d", b[i][j]);
                else printf("*");
            }
            printf("\n");
        }
        return 0;
    }
    
    #include <iostream>//升级版
    using namespace std;
    const int N = 1010;
    char a[N][N];
    int b[N][N];
    int dx[] = {0,1,1,1,0,-1,-1,-1};//偏移量
    int dy[] = {1,1,0,-1,-1,-1,0,1};
    int main()
    {
        int n, m;
        cin >> n >> m;
        for (int i = 1; i <= n; ++i)
        {
            for (int j = 1; j <= m; ++j)
            {
                cin >> a[i][j];
            }
        }
        for (int i = 1; i <= n; ++i)
        {
            for (int j = 1; j <= m; ++j)
            {
                int sum = 0;
                for (int k = 0; k < 8; ++k)
                {
                    int x = i + dx[k],y = j + dy[k];
                    if (a[x][y] == '*') ++sum;
                }
                b[i][j] = sum;
            }
        }
        for (int i = 1; i <= n; ++i)
        {
            for (int j = 1; j <= m; ++j)
            {
                if (a[i][j] != '*') printf("%d", b[i][j]);
                else printf("*");
            }
            printf("\n");
        }
        return 0;
    }
    
    
    • 1

    信息

    ID
    5411
    时间
    1000ms
    内存
    256MiB
    难度
    1
    标签
    递交数
    13
    已通过
    4
    上传者