我试图将矩阵中选定的一组元素水平地和垂直地移动一定距离。
我使用Java作为输入:
Point对象数组)Point对象,Point.x -水平移位,Point.y -垂直)例如,将所有字母按1位置向右移动如下所示:
From:
A B 0 1
2 C 3 4
5 6 7 8
To:
0 A B 1
2 3 C 4
5 6 7 8另一个例子是,字母水平移动一个位置,垂直移动一个字母:
From:
A B 0 1
C D 2 3
4 5 6 7
To:
6 2 0 1
5 A B 3
4 C D 7(请注意数字如何填补所造成的空白)
长距离移动元素很容易,因为没有重叠,但是现在我仍然停留在上面的例子上。
另一个例子(简单的例子,没有重叠)。将同一正方形移动(2,2):
From:
A B 0 1
C D 2 3
4 5 6 7
8 9 10 11
To:
6 7 0 1
10 11 2 3
4 5 A B
8 9 C D发布于 2013-04-26 22:43:21
我尝试了一种方法,当带有Point对象的数组(需要移动的)降序排序时,它实际上是工作的
public static void main(String[] args) {
// first an example matrix with chars to fit your example
char[][] matrix = new char[3][];
matrix[0] = new char[]{'A', 'B', '0', '1'};
matrix[1] = new char[]{'C', 'D', '2', '3'};
matrix[2] = new char[]{'4', '5', '6', '7'};
// then the elements you want to move (the highest index first!)
Point[] elements = new Point[]{
new Point(1, 1),
new Point(1, 0),
new Point(0, 1),
new Point(0, 0)
};
// the direction indicates with where the element has to go to from it's current index. So (1,1) means one right, one down
Point directionPoint = new Point(1, 1);
// print the matrix to see what the original looks like
printMatrix(matrix);
// iterate through the elements that have to be moved
for (Point p : elements) {
move(p, directionPoint, matrix);
printMatrix(matrix);
}
}
// this method takes one element, the direction and the matrix and moves this one element by switching it with the element that is at its destination index
public static void move(Point elementToMove, Point direction, char[][] matrix) {
char temp = matrix[elementToMove.x][elementToMove.y];
matrix[elementToMove.x][elementToMove.y] = matrix[elementToMove.x + direction.x][elementToMove.y + direction.y];
matrix[elementToMove.x + direction.x][elementToMove.y + direction.y] = temp;
}
// just a simple print method to see the current matrix
public static void printMatrix(char[][] matrix) {
for (char[] row : matrix) {
String line = "";
for (int i = 0; i < row.length; i++) {
line += row[i] + " ";
}
System.out.println(line);
}
System.out.println("---");
}当我运行它时,这是结果(第一个矩阵是原始的,最后一个矩阵是结果):
A B 0 1
C D 2 3
4 5 6 7
---
A B 0 1
C 6 2 3
4 5 D 7
---
A B 0 1
5 6 2 3
4 C D 7
---
A 2 0 1
5 6 B 3
4 C D 7
---
6 2 0 1
5 A B 3
4 C D 7 现在我知道这可能不是最优雅的解决方案,我几乎可以肯定,它并不是对所有可能的情况都是完整的,但它表明,当元素被排序时,“转移”是有效的。您只需开始使用最后一个元素(当您想要向右移动时)。当然,如果您想转移到左边(可能是direction=(0,-1)),您需要从第一个元素开始.诸若此类
发布于 2013-04-26 22:01:12
只需复制一份你的矩阵。
设a=原始矩阵
设b=你的目标矩阵
在移动之前,让b= a;
如果你想把ai转到ap,先把ai转到bp。
那么,我们应该决定填补这一空白的数字:
For every cell(i,j):
Step 1. Check if the cell will be a gap after the move, if not do nothing.
Step 2. find where the cell moves(denotes by (x,y)).
Step 3. If (x,y) is not a number before the move then repeat Step 2,
else we can say after the move b[i][j] is a[x][y].移动完成后,只需将数组b复制到数组a,然后执行下一步移动。
https://stackoverflow.com/questions/16245761
复制相似问题