取消函数的使用改写上述代码
时间: 2024-09-29 08:16:01 浏览: 31
取消函数后,代码会变得更紧凑,但仍保持清晰。我们将直接在主循环中检查并执行消除操作。以下是取消函数后的代码:
```java
import java.util.Scanner;
public class EliminationGame {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int m = scanner.nextInt();
int[][] board = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
board[i][j] = scanner.nextInt();
}
}
// 直接在主循环内检查并消除
for (int i = 0; i < n; i++) {
for (int j = 0; j < m - 2; j++) {
if (eliminateLineAndColumn(board, i, j)) {
// 避免重复消除,仅在当前操作后更新对应区域
if (board[i][j] > 0) {
board[i][j] = 0;
if (i > 0 && eliminateLineAndColumn(board, i - 1, j)) continue;
if (j > 0 && eliminateLineAndColumn(board, i, j - 1)) continue;
}
}
}
}
// 输出结果
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
System.out.print(board[i][j] > 0 ? board[i][j] : "0 ");
}
System.out.println();
}
}
// 合并检查和消除的逻辑
private static boolean eliminateLineAndColumn(int[][] board, int row, int col) {
int count = 1;
if (checkLine(board, row, col) || checkColumn(board, col, row)) {
for (int delta = 1; delta <= 2; delta++) {
if (count >= 3) {
for (int dir = 0; dir < 2; dir++) {
int newRow = row + (dir == 0 ? delta : 0);
int newCol = col + (dir == 1 ? delta : 0);
while (newRow >= 0 && newRow < board.length && newCol >= 0 && newCol < board[0].length) {
board[newRow][newCol] = 0;
newRow += dir;
newCol += dir;
}
}
return true;
}
count = 1;
}
}
return false;
}
}
```
这段代码去掉了`checkLine`和`checkColumn`两个函数,将它们的逻辑整合到`eliminateLineAndColumn`方法中。这样处理虽然减少了函数调用,但是代码可能会稍微复杂一些。
阅读全文