字节跳动第二次笔试 80,20,70,10
字节跳动第二次笔试 80,20,70,10
第三题,2048游戏
import java.util.*; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = 4; int s = in.nextInt(); int[][] arr = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { arr[i][j] = in.nextInt(); } } if (s == 1) { for (int j = 0; j < 4; j++) { for (int i = 0; i < n - 1; i++) { if (arr[i][j] == arr[i + 1][j]) { arr[i][j] *= 2; arr[i + 1][j] = 0; } } int t = 0; for (int i = 0; i < n; i++) { if (arr[i][j] != 0) { arr[t][j] = arr[i][j]; t++; } } while (t < n) { arr[t][j] = 0; t++; } } } else if (s == 2) { for (int j = 0; j < 4; j++) { for (int i = n - 1; i > 0; i--) { if (arr[i][j] == arr[i - 1][j]) { arr[i][j] *= 2; arr[i - 1][j] = 0; } } int t = n - 1; for (int i = n - 1; i >= 0; i--) { if (arr[i][j] != 0) { arr[t][j] = arr[i][j]; t--; } } while (t >= 0) { arr[t][j] = 0; t--; } } } else if (s == 3) { for (int i = 0; i < n - 1; i++) { for (int j = 0; j < n - 1; j++) { if (arr[i][j] == arr[i][j + 1]) { arr[i][j] *= 2; arr[i][j + 1] = 0; } } int t = 0; for (int j = 0; j < n; j++) { if (arr[i][j] != 0) { arr[i][t] = arr[i][j]; t++; } } while (t < n) { arr[i][t] = 0; t++; } } } else if (s == 4) { for (int i = 0; i < n - 1; i++) { for (int j = n - 1; j > 0; j--) { if (arr[i][j] == arr[i][j - 1]) { arr[i][j] *= 2; arr[i][j - 1] = 0; } } int t = n-1; for (int j = n - 1; j >= 0; j--) { if (arr[i][j] != 0) { arr[i][t] = arr[i][j]; t--; } } while (t>=0) { arr[i][t] = 0; t--; } } } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { System.out.print(arr[i][j] + " "); } System.out.println(); } } }