字节跳动2048核心逻辑
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (input.hasNext()) {
int gesture = input.nextInt();
int[][] matrix = new int[4][4];
for (int i = 0; i < 4; i ) {
for (int j = 0; j < 4; j ) {
matrix[i][j] = input.nextInt();
}
}
getResult(gesture, matrix);
int j;
for (int i = 0; i < 4; i ) {
for (j = 0; j < 3; j ) {
System.out.print(matrix[i][j] " ");
}
System.out.println(matrix[i][j]);
}
}
}
private static void getResult(int gesture, int[][] matrix) {
switch (gesture) {
//1�����
case 1:
Up(matrix);
break;
//2�����
case 2:
Down(matrix);
break;
case 3:
MoveLeft(matrix);
break;
case 4:
MoveRight(matrix);
break;
default:
break;
}
}
private static void MoveRight(int[][] params) {
for (int i = 0; i < 4; i ) {
rightclear(params);
for (int j = 3; j > 0; j--) {
if (params[i][3] != 0) {
if (params[i][j] == params[i][j - 1]) {
params[i][j] = (params[i][j]);
params[i][j - 1] = 0;
}
}
}
rightclear(params);
}
}
public static void rightclear(int[][] params) {
for (int i = 0; i < 4; i ) {
for (int j = 3; j > 0; j--) {
int k = j;
while (k > 0 && params[i][k] == 0) {
params[i][k] = params[i][k - 1];
params[i][k - 1] = 0;
k--;
}
}
}
}
private static void MoveLeft(int[][] params) {
for (int i = 0; i < 4; i ) {
leftclear(params);
for (int j = 0; j < 3; j ) {
if (params[i][0] != 0) {
if (params[i][j] == params[i][j 1]) {
params[i][j] = (params[i][j 1]);
params[i][j 1] = 0;
}
}
}
leftclear(params);
}
}
private static void leftclear(int[][] params) {
for (int i = 0; i < 4; i ) {
for (int j = 0; j < 3; j ) {
int k = j;
while (k >= 0 && params[i][k] == 0) {
params[i][k] = params[i][k 1];
params[i][k 1] = 0;
k--;
}
}
}
}
private static void Down(int[][] params) {
for (int j = 0; j < 4; j ) {
downclear(params);
for (int i = 3; i > 0; i--) {
if (params[3][j] != 0) {
if (params[i][j] == params[i - 1][j]) {
params[i][j] = (params[i][j]);
params[i - 1][j] = 0;
}
}
}
downclear(params);
}
}
private static void downclear(int[][] params) {
for (int j = 0; j < 4; j ) {
for (int i = 3; i > 0; i--) {
int k = i;
while (k > 0 && params[k][j] == 0) {
params[k][j] = params[k - 1][j];
params[k - 1][j] = 0;
k--;
}
}
}
}
private static void Up(int[][] matrix) {
for (int j = 0; j < 4; j ) {
upclear(matrix);
for (int i = 0; i < 3; i ) {
if (matrix[0][j] != 0) {
if (matrix[i][j] == matrix[i 1][j]) {
matrix[i][j] = matrix[i][j];
matrix[i 1][j] = 0;
}
}
}
upclear(matrix);
}
}
private static void upclear(int[][] params) {
for (int j = 0; j < 4; j ) {
for (int i = 0; i < 3; i ) {
int k = i;
while (k >= 0 && params[k][j] == 0) {
params[k][j] = params[k 1][j];
params[k 1][j] = 0;
k--;
}
}
}
}
}