反向俄罗斯方块开发:如何将方块放置在最小行列索引处?
反向俄罗斯方块:方块放置到最小行列索引位置的实现问题
问题描述
我正在开发反向俄罗斯方块,需要将一个r×c的俄罗斯方块矩阵,放置到m×n游戏场地的最小行、列索引位置。已知:
int[][] field:游戏场地整数矩阵,0代表空位置,1代表已填充boolean[][] fieldbool:同尺寸布尔矩阵,true对应场地可放置位置,false对应已被占用的位置int[][] figure:待放置的俄罗斯方块矩阵,1代表方块的填充部分
示例数据
- 游戏场地:
int[][] field = {{0, 0, 0, 0, 0},{0, 0, 0, 0, 0},{0, 0, 0, 0, 0},{1, 1, 0, 1, 0},{1, 0, 1, 0, 1}};
- 俄罗斯方块:
int[][] figure = {{1, 1, 1}, {1, 0, 1}, {1, 0, 1}};
- 布尔场地矩阵:
boolean[][] fieldbool = {{true, true, true, true, true}, {true, true, true, true, true}, {true, true, true, true, true}, {false, false, true, true, true}, {false, false, false, true, false}};
期望输出
放置后的场地矩阵:
int[][] field = {{1, 1, 1, 0, 0},{1, 0, 1, 0, 0},{1, 0, 1, 0, 0},{1, 1, 0, 1, 0},{1, 0, 1, 0, 1}};
当前尝试的问题
我试过统计行/列中true的数量,当数量等于方块的高/宽时,从当前索引倒推填充场地,但输出和原场地完全一致,方块根本没放进去。
解决方案思路与代码实现
核心逻辑是从最小索引开始遍历,找到第一个能完整放下方块的左上角坐标,然后填充场地。
步骤拆解
- 先获取方块和场地的尺寸
- 从行索引0、列索引0开始,遍历所有可能的方块起始位置(要保证方块不会超出场地边界)
- 对每个起始位置,检查方块所有1对应的场地位置是否都是可放置的(
fieldbool为true) - 找到第一个符合条件的位置后,立即将方块的1填充到场地对应位置,停止遍历
Java代码实现
public class ReverseTetris { public static void placeFigure(int[][] field, boolean[][] fieldbool, int[][] figure) { int fieldRows = field.length; int fieldCols = field[0].length; int figRows = figure.length; int figCols = figure[0].length; // 从最小索引开始遍历所有可行的起始位置 for (int rowStart = 0; rowStart <= fieldRows - figRows; rowStart++) { for (int colStart = 0; colStart <= fieldCols - figCols; colStart++) { boolean canPlace = true; // 检查当前起始位置能否放下整个方块 for (int i = 0; i < figRows; i++) { for (int j = 0; j < figCols; j++) { // 只需要检查方块中是1的位置 if (figure[i][j] == 1 && !fieldbool[rowStart + i][colStart + j]) { canPlace = false; break; } } if (!canPlace) break; } // 找到可行位置,填充场地并退出 if (canPlace) { for (int i = 0; i < figRows; i++) { for (int j = 0; j < figCols; j++) { if (figure[i][j] == 1) { field[rowStart + i][colStart + j] = 1; } } } return; } } } } // 测试示例 public static void main(String[] args) { int[][] field = {{0, 0, 0, 0, 0},{0, 0, 0, 0, 0},{0, 0, 0, 0, 0},{1, 1, 0, 1, 0},{1, 0, 1, 0, 1}}; int[][] figure = {{1, 1, 1}, {1, 0, 1}, {1, 0, 1}}; boolean[][] fieldbool = {{true, true, true, true, true}, {true, true, true, true, true}, {true, true, true, true, true}, {false, false, true, true, true}, {false, false, false, true, false}}; placeFigure(field, fieldbool, figure); // 打印结果 System.out.println("最终场地矩阵:"); for (int[] row : field) { System.out.println(java.util.Arrays.toString(row)); } } }
代码说明
- 遍历顺序保证了找到的第一个可行位置就是最小的行、列索引位置
- 只检查方块中为1的位置,避免无效判断
- 填充时只修改场地中对应方块的位置,保留原有场地的已填充内容
内容的提问来源于stack exchange,提问作者Tanya Fondaj
相关产品推荐
相关产品推荐

