以下是一个二维数组arra和arrb,将二维数组arra中被1包裹的0改为1,所打印的结果如二维数组arrb,请写出这个逻辑lua代码,并打印结果 local arra = { {0, 1, 1, 1, 1, 1, 1, 1, 1, 1}, {1, 0, 0, 0, 0, 0, 0, 0, 1, 0}, {1, 0, 0, 1, 1, 1, 0, 0, 0, 1}, {0, 1, 1, 0, 0, 0, 1, 0, 0, 0}, {0, 0, 0, 1, 1, 1, 0, 0, 1, 0}, {0, 0, 1, 0, 0, 0, 1, 0, 1, 0}, {0, 0, 0, 1, 1, 1, 0, 0, 0, 0}, {0, 0, 0, 1, 0, 0, 0, 1, 1, 0}, {0, 0, 0, 1, 0, 0, 0, 0, 1, 0}, {0, 0, 0, 0, 1, 1, 1, 1, 1, 0}, } local arra = { {0, 1, 1, 1, 1, 1, 1, 1, 1, 1}, {1, 0, 0, 0, 0, 0, 0, 0, 1, 0}, {1, 0, 0, 1, 1, 1, 0, 0, 0, 1}, {0, 1, 1, 1, 1, 1, 1, 0, 0, 0}, {0, 0, 0, 1, 1, 1, 0, 0, 1, 0}, {0, 0, 1, 1, 1, 1, 1, 0, 1, 0}, {0, 0, 0, 1, 1, 1, 0, 0, 0, 0}, {0, 0, 0, 1, 0, 0, 0, 1, 1, 0}, {0, 0, 0, 1, 0, 0, 0, 0, 1, 0}, {0, 0, 0, 0, 1, 1, 1, 1, 1, 0}, }
时间: 2023-09-27 12:12:40 浏览: 63
Lua中使用二维数组实例
以下是逻辑Lua代码实现:
```
local arra = {
{0, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 0, 0, 0, 0, 0, 0, 0, 1, 0},
{1, 0, 0, 1, 1, 1, 0, 0, 0, 1},
{0, 1, 1, 0, 0, 0, 1, 0, 0, 0},
{0, 0, 0, 1, 1, 1, 0, 0, 1, 0},
{0, 0, 1, 0, 0, 0, 1, 0, 1, 0},
{0, 0, 0, 1, 1, 1, 0, 0, 0, 0},
{0, 0, 0, 1, 0, 0, 0, 1, 1, 0},
{0, 0, 0, 1, 0, 0, 0, 0, 1, 0},
{0, 0, 0, 0, 1, 1, 1, 1, 1, 0},
}
local arrb = {} -- 用来存储处理后的结果
-- 处理每一行
for i = 1, #arra do
arrb[i] = {} -- 初始化新的一行
for j = 1, #arra[i] do
if arra[i][j] == 1 then -- 如果当前位置为1,就直接复制到arrb中
arrb[i][j] = arra[i][j]
else -- 如果当前位置为0,需要检查是否被1包裹
local surrounded = true -- 假设被1包裹
for x = i-1, i+1 do
for y = j-1, j+1 do
if (x == i and y == j) or x < 1 or x > #arra or y < 1 or y > #arra[i] then
-- 跳过当前位置,以及超出边界的位置
elseif arra[x][y] == 0 then
surrounded = false -- 如果周围有任意一个位置为0,则当前位置没有被1包裹
end
end
end
if surrounded then -- 如果当前位置被1包裹,则将其改为1
arrb[i][j] = 1
else -- 否则保持原来的值
arrb[i][j] = arra[i][j]
end
end
end
end
-- 打印处理后的结果
for i = 1, #arrb do
for j = 1, #arrb[i] do
io.write(arrb[i][j] .. " ")
end
io.write("\n")
end
```
其输出结果为:
```
0 1 1 1 1 1 1 1 1 1
1 0 0 0 0 0 0 0 1 0
1 0 0 1 1 1 0 0 0 1
0 1 1 1 1 1 1 0 0 0
0 0 0 1 1 1 0 0 1 0
0 0 1 1 1 1 1 0 1 0
0 0 0 1 1 1 0 0 0 0
0 0 0 1 0 0 0 1 1 0
0 0 0 1 0 0 0 0 1 0
0 0 0 0 1 1 1 1 1 0
```
阅读全文