1

澄清一下,我只想要一两个 for 循环来帮助我,最好是与我在垂直中使用的样式相同:)

我正在使用 2D 数组制作游戏,我需要检查以测试在当前位置(由绿色方块表示)是否存在字符的“​​l”多个对角线序列的一部分。

4

2 回答 2

1

这是功能,它有效。解释在代码中的注释中,但如果你发现任何令人困惑的地方,请告诉我,我会解释它。

public static boolean diagonals(char[][] b, int row, int col, int l) {
  int forwardCounter = 1; // this counts top right to bottom left
  int backCounter = 1; // this counts top left to bottom right
  int distance = 1;
  // 0 = topleft, 1 = topright, 2 = bottomleft, 3 = bottomright
  boolean[] checks = new boolean[]{true, true, true, true};

  char charAtPosition = b[row][col];

  while(checks[0] || checks[1] || checks[2] || checks[3]) {
    for(int i = 0; i < 4; i++) {
      if(checks[i]) {
        // This looks confusing but it's simply just converting i into
        // The four different directions
        checks[i] = checkSquare(b, row + (i < 2 ? -distance : distance),
                col + (i % 2 == 0 ? -distance : distance), charAtPosition);
        if(checks[i]) {
          // If top left or bottom right
          if(i % 3 == 0) {
            backCounter++;
          } else {
            forwardCounter++;
          }
        }
      }
    }

    if (forwardCounter >= l || backCounter >= l) return true;

    distance++;
  }

  return false;
}

private static boolean checkSquare(char[][] b, int row, int col, char check) {
  if(row < 0 || row >= b.length) return false;
  if(col < 0 || col >= b[0].length) return false;

  return check == b[row][col];
}
于 2012-12-04T15:09:50.063 回答
1
public static boolean diagonals(char[][] b, int row, int col, int l) {

            int counter = 1; // because we start from the current position
            char charAtPosition = b[row][col];
            int numRows = b.length;
            int numCols = b[0].length;
            int topleft = 0;
            int topright = 0;
            int bottomleft = 0;
            int bottomright = 0;
            for (int i=row-1,j=col-1;i>=0 && j>=0;i--,j--) {
                if (b[i][j]==charAtPosition) {
                    topleft++;
                } else {
                    break;
                }
            }
            for (int i=row-1,j=col+1;i>=0 && j<=numCols;i--,j++) {
                if (b[i][j]==charAtPosition) {
                    topright++;
                } else {
                    break;
                }
            }
            for (int i=row+1,j=col-1;i<=numRows && j>=0;i++,j--) {
                if (b[i][j]==charAtPosition) {
                    bottomleft++;
                } else {
                    break;
                }
            }
            for (int i=row+1,j=col+1;i<=numRows && j<=numCols;i++,j++) {
                if (b[i][j]==charAtPosition) {
                    bottomright++;
                } else {
                    break;
                }
            }
            return topleft + bottomright + 1 >= l || topright + bottomleft + 1 >= l; //in this case l is 5
    }

这个想法是我们沿着四个方向走并计算步数。这可能不是最有效的实现,但至少它看起来简洁且易于理解。

于 2012-12-04T15:48:25.830 回答