C解,有人能解释一下这段代码给我
C solution, can someone explain this code to me?
我的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数组ctr
和field
。field
的部分字段包含*
假设这个二维数组
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
相关文章:
- 在java中解决这段代码时面临循环中的问题
- 我是如何在这段代码中出现分段错误的
- 我不明白这段代码是如何对这个pythonlist()进行排序的,也不明白如何用C++中的向量来重现它
- 为什么这段代码不起作用,我该如何解决?
- 为什么这段代码给我错误? 有没有自错?
- 有人可以解释一下这段代码如何能够反转字符串
- 可能我知道为什么这段代码没有给出任何输出吗?
- 这段代码的最后一行在做什么?
- 我不知道为什么这段代码会让核心被转储?
- 我试图用这段代码找到二叉树的高度,但它一直返回 0,有人可以告诉我为什么吗?
- 有人可以向我解释一下这段代码的作用吗?
- 存储在哪个内存段(代码/数据段)类(员工)中?
- 为什么这段代码会导致无限循环?
- 任何人都可以弄清楚这段代码如何显示运行错误?它打印无限时间 -1 以及正确答案
- 如何为一段代码启用 -permissive
- 谁能告诉我为什么这段代码没有产生正确的输出?
- 我想反转我的阵列.为什么这段代码给出垃圾值?
- 有人可以向我解释一下这段代码是如何工作的吗?(程序在预期数值且用户输入其他输入时再次要求用户输入)
- 有人可以解释一下这段代码中发生了什么吗?(数组)
- C解,有人能解释一下这段代码给我