在11x11矩阵中找到3x3矩阵有更简单的方法吗?

时间:2020-05-03 19:41:13

标签: java algorithm matrix

我和几个朋友正在使用Java创建一个基于模拟的游戏,其中我们的“玩家”在11x11矩阵上充满一个名为Chunk的类。为了使玩家能够与周围的世界进行互动,这要求我们在围绕玩家的3x3中查看块的信息。

示例(较小的矩阵,x =那里没有,o =人):

xxxxxxxxxxx
xxxxxxxxxxx
xxxxxoxxxxx
xxxxxxxxxxx
xxxxxxxxxxx

我们需要能够收集玩家(o)周围的块(在这种情况下,行的[1],[2],[3]和col的[4],[5],[6])。当然,3x3矩阵不能离开矩阵的边界,如果这样做,我们将忽略那些不存在的边界并收集可以收集的块。当前,我们有一段代码可以完成所需的任务,但是我们觉得可以更快,更干净或者完全以其他方式重新制作它。

fullMap 是一个数组,已初始化为11x11的Chunk数组,并且 currentRow currentCol 都是与玩家当前在fullMap中的位置有关的整数。

for(int row = 0; row < fullMap.length; row++) {
      for (int col = 0; col < fullMap[row].length; col++) {
            if (((row == currentRow-1) && (col == currentCol)) && currentRow != 0) {
                //store the chunk
            } else if (((row == currentRow-1) && (col == currentCol+1)) && (currentRow != 0 && currentCol != 10)) {
                //store the chunk
            } else if (((row == currentRow-1) && (col == currentCol-1)) && (currentRow != 0 && currentCol != 0)) {
                //store the chunk
            } else if (((row == currentRow) && (col == currentCol+1)) && currentCol != 10) {
                //store the chunk
            } else if (((row == currentRow) && (col == currentCol-1))  && currentCol != 0) {
                //store the chunk
            } else if (((row == currentRow+1) && (col == currentCol+1)) && (currentRow != 10 && currentCol != 10)){
                //store the chunk
            } else if (((row == currentRow+1) && (col == currentCol)) && currentRow != 10) {
                //store the chunk
            } else if (((row == currentRow+1) && (col == currentCol-1)) && (currentRow != 10 && currentCol != 0)){
                //store the chunk
            }
    }
}

如果需要其他信息,我很乐意将其发布。

1 个答案:

答案 0 :(得分:2)

您不需要遍历fullMap,对吗? 您知道(currentRowcurrentCol),从那里您在每个方向上走了-1 / + 1。总共将有9个字段需要检查。

    ...
    for (int i = -1; i <= 1; i++) {
      for (int j = -1; j <= 1 ; j++) {
        if (isMovePossible(currentRow + i, currentCol + j)) {
          // store chunk
        }
      }
    }
    ...


  private static boolean isMovePossible(int row, int col) {
    return row >= 0 && row <= 10 && col >= 0 && col <=10;
  }