Java中如何从随机位置开始遍历矩阵
我正在尝试编写一个简单的 Java 程序,它可以从用户指定的矩阵中的任何位置开始遍历矩阵(二维数组)。
我首先声明我的矩阵并用随机数填充它,但我不知道从这里去哪里?我怎样才能从随机位置开始遍历矩阵中的每个单元格?
我只是想要一些基本的东西,而不是非常高级的东西,因为我仍然是 Java 的初学者,任何帮助将不胜感激!
public static void main(String[] args) {
// Initialize Matrix randomly
int R = 3;
int C = 3;
int[][] matrix = new int[R][C];
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
matrix[i][j] = ((int) (Math.random() * 2));
}
}
//---------------------------
// Robot Moving Algorithm
int i, j, rows=R, cols=C, m, n;
int Robot_i=0, Robot_j=0;
if (Robot_i==0) {
for (i=Robot_i; i<rows; i++) {
}
}
}
以下是我正在寻找的内容的概述:
8 5 1
7 3 2
6 9 4
预期输出,从第 0 行第 1 列开始:5,1,2,4,9,6,7,8,3
I'm trying to write a simple Java program that can traverse a matrix (2D-Array) starting from any position in the matrix that the user specifies.
I started by declaring my matrix and filling it with random numbers, but I'm not sure where to go from here? How can I be able to traverse every cell in my matrix starting from a random position?
I'm just looking to have something basic and not very advanced because I'm still a beginner in Java, any help would be much appreciated!
public static void main(String[] args) {
// Initialize Matrix randomly
int R = 3;
int C = 3;
int[][] matrix = new int[R][C];
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
matrix[i][j] = ((int) (Math.random() * 2));
}
}
//---------------------------
// Robot Moving Algorithm
int i, j, rows=R, cols=C, m, n;
int Robot_i=0, Robot_j=0;
if (Robot_i==0) {
for (i=Robot_i; i<rows; i++) {
}
}
}
Here's an overview of what I'm looking for:
8 5 1
7 3 2
6 9 4
expected output, starting from row 0, col 1: 5,1,2,4,9,6,7,8,3
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
假设我们有这个矩阵:
您也可以将其视为数组
[9, 5, 9, 1, 0, 3, 1, 2, 0]
并且您可以将矩阵中的任何坐标映射到数组中相应的索引,例如:
坐标第 2 行、第 1 列处的
2
具有索引 7这里有 2 种将坐标映射到索引的方法,反之亦然
这是一个打印矩阵的实用方法
现在使用这些工具:
打印出:
Let's say we have this matrix:
you can also think of it as an array
[9, 5, 9, 1, 0, 3, 1, 2, 0]
and you can map any coordinates in the matrix to its corresponding index in the array, ex:
the
2
at coordinates row 2, col 1 has index 7here are 2 methods to map coords to index and vice versa
And here is a utility method to print your matrix
Now with these tools:
prints out: