[英]Matrix manipulation (rotation/rolling)
我有这个3x3矩阵:
{
[1,2,3],
[4,5,6],
[7,8,9]
}
假设如果我发送两个参数m和n,则此矩阵必须移动m和n个位置(m个正向/向右移动或负向左移动)和(n个正向/向下移动或n个负向向上移动)。 对于样本,如果我发送m = 1,n = 0:
{
[3, 1, 2],
[6, 4, 5],
[9, 7, 8]
}
有某种方法可以做到这一点吗? 还是仅仅是“辛苦的手工”?
如果准备使用List<List<Integer>>
代替int[][]
,则可以使用Collections.rotate(List list,int distance) 。
private void rotate(List<List<Integer>> matrix, int m, int n) {
for (List<Integer> row : matrix) {
Collections.rotate(row, m);
}
Collections.rotate(matrix, n);
}
public void test() {
int[][] m = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
List<List<Integer>> matrix = new ArrayList<>();
for (int[] r : m) {
List<Integer> row = new ArrayList<>();
for (int v : r) {
row.add(v);
}
matrix.add(row);
}
System.out.println("Before: " + matrix);
rotate(matrix, 1, 2);
System.out.println("After: " + matrix);
}
打印:
之前:[[1、2、3],[4、5、6],[7、8、9]
之后:[[3,1,2],[6,4,5],[9,7,8]]
这与您的预期稍有不同,但是看起来很有意义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.