我想撰寫一個在所有 4 個方向上移動零并通過在控制臺中移動零來更新地圖的方法,我該怎么做?
public static void main(String args[]) {
String[][] map = {
{".",".","."},
{".","0","."},
{".",".","."}
};
for(int i=0;i<map.length;i ){
for(int j=0;j<map[i].length;j ){
System.out.print(map[i][j] " ");
}
System.out.println();
}
}
沒有任何限制或任何東西,我只想弄清楚如何以任何方式移動零。
uj5u.com熱心網友回復:
您撰寫的代碼只會嘗試列印您的矩陣。如果要在矩陣周圍移動“0”元素,首先需要定義一個enum
來確定方向,然后一個move()
給定方向d
和矩陣的方法m
將相應地移動“0”元素。
元素移動只是一個旋轉,通過處理邊緣情況(行和列的邊界)來增加或減少相應的索引。
public class Main {
public enum Direction {
UP, DOWN, LEFT, RIGHT
}
public static void move(Direction move, String[][] matrix) {
int row = -1, col = -1, newRow, newCol;
String temp;
//Finding the position of the "0" element
for (int i = 0; i < matrix.length; i ) {
for (int j = 0; j < matrix[i].length; j ) {
if (matrix[i][j].equals("0")) {
row = i;
col = j;
break;
}
}
if (row != -1) break;
}
//If not 0 element is found then the method is terminated
if (row < 0 || col < 0) {
return;
}
switch (move) {
case UP:
newRow = row - 1 < 0 ? matrix.length - 1 : row - 1;
temp = matrix[newRow][col];
matrix[newRow][col] = matrix[row][col];
matrix[row][col] = temp;
break;
case DOWN:
newRow = (row 1) % matrix.length;
temp = matrix[newRow][col];
matrix[newRow][col] = matrix[row][col];
matrix[row][col] = temp;
break;
case LEFT:
newCol = col - 1 < 0 ? matrix[row].length - 1 : col - 1;
temp = matrix[row][newCol];
matrix[row][newCol] = matrix[row][col];
matrix[row][col] = temp;
break;
case RIGHT:
newCol = (col 1) % matrix[row].length;
temp = matrix[row][newCol];
matrix[row][newCol] = matrix[row][col];
matrix[row][col] = temp;
break;
}
}
這是一個測驗可能實作的鏈接
https://www.jdoodle.com/iembed/v0/s63
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/490495.html
下一篇:一些但不是其他的SQL聚合更新