doucong8553 2015-05-22 22:25
浏览 43
已采纳

计算二维数组中的所有数字

I'm trying to write console minesweeper, but cant figure out how to iterate over 2d array, and count amount of "-1" around each of element. My array looks like

[0 0 0 0 0]
[0 0 -1 0 0]
[0 0 0 0 0]
[0 0 0 -1 -1]
[0 0 0 -1 -1]

Where "-1" that is mine. I've tried to simply iterate over it with code

for i := 0; i < row; i++ {
numb := 0
    for j := 0; j < col; j++ {
         if ary[i-1][j-1] == -1 {
             numb ++ } 
         }
         if ary[i-1][j] == 1 {
             numb ++ }
         //rest of code omitted

    }

But that resulted in huge amout of code, which is hard to read and understand. Is there more flexible way, to check all elements around current in for-iterator, so in result it would look like

[0 1  1   1 0]
[0 1 -1   1 0]
[0 1  2   2 1]
[0 0  1  -1 -1]
[0 0  1  -1 -1]
  • 写回答

1条回答 默认 最新

  • dongyou26216708 2015-05-22 22:40
    关注
    for i := 0; i < row; i++ {
        for j := 0; j < col; j++ {
            if ary[i][j] == -1 {
                for k := max(0, i - 1); k <= min(row - 1, i + 1); k++ {
                    for l := max(0, j - 1); l <= min(col - 1, j + 1); l++ {
                        if ary[k][l] != -1 {
                            ary[k][l] ++
                        }
                    }
                } 
            }
        }
    }
    

    The first two outer loops go through the array. If the observed number is -1 then it increases all surrounding cells unless there is a mine on that field. To avoid the checks if ary[k][l] is not outside of bounds the bounds are calculated before by using the trick with min / max to ensure that k and l are not outside of bounds. E.g. max(0, i-1) will always return i-1 unless i-1 is smaller than 0, then it returns 0.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号