C解,有人能解释一下这段代码给我

C solution, can someone explain this code to me?

本文关键字:一下 段代码 代码 能解释      更新时间:2023-10-16

我的c++老师为我们提供了一个问题的解决方案,其中有一部分我不明白发生了什么。有人能给我解释一下吗?M和n正在从文本文件中读取,以定义数组的大小。

for (int row=0; row < m; row++) {
    for (int col = 0; col < n; col++) {
        if (field[row][col] =='*') {
            ctr[row - 1][col - 1]++;
            ctr[row - 1][col]++;
            ctr[row - 1][col + 1]++;
            ctr[row][col - 1]++;
            ctr[row][col + 1]++;
            ctr[row + 1][col - 1]++;
            ctr[row + 1][col]++;
            ctr[row + 1][col + 1]++;
        }
    }
}

它将矩阵中星星(*)周围的所有方块的值加1。

首先搜索*,然后增加星星周围所有8个方块的值。

假设矩阵field的一部分如下:

     |    |  
+----+----+---+
     |  * |  
+----+----+---+
     |    |  

下面的ctr相似
   1 |  1 | 1
+----+----+---+
   1 |  1 | 1
+----+----+---+
   1 |  1 | 1

ctr

   2 |  2 | 2
+----+----+---+
   2 |  1 | 2
+----+----+---+
   2 |  2 | 2

逻辑如上所述。但是,当星号靠近边界时,要注意访问冲突

您有两个2D数组ctrfieldfield的部分字段包含*

假设这个二维数组

field        ---->row
       . | .  | .
    +----+----+---+
 |     . |  * | .
 |  +----+----+---+
 c     . |  . | .
 o
 l

将给出

   ctr        ---->row
       1 | 1  | 1
   | +----+----+---+
   |   1 |  * | 1
   c +----+----+---+
   o   1 |  1 | 1
   l

代码:

for (int row=0; row < m; row++) {
    for (int col = 0; col < n; col++) {
        if (field[row][col] =='*') { //Assume center of the field array contains *
            ctr[row - 1][col - 1]++; //incr elemnt at previous row, previous col
            ctr[row - 1][col]++;     //incr elemnt on previous row, same col
            ctr[row - 1][col + 1]++; //incr elemnt on previous row, next col
            ctr[row][col - 1]++;     //incr elemnt on same row, previous col
            ctr[row][col + 1]++;     //incr elemnt on same row, next col
            ctr[row + 1][col - 1]++; //incr elemnt on next row, previous col
            ctr[row + 1][col]++;     //incr elemnt on next row, same col
            ctr[row + 1][col + 1]++; //incr elemnt on next row, next col
        }
    }
}

在"Field"矩阵中查找a *

然后取*的位置,并将*在"ctr"矩阵中位置周围的值加1