【发布时间】:2021-03-09 13:50:24
【问题描述】:
我有一个定义大小为 n x n 的矩阵。在矩阵网格的每个索引处,都有一个整数值。网格是通过每隔 n 个值包装整数来创建的。请参阅下面的 4x4 示例,从字符串输入“6 4 7 5 3 8 9 2 1 5 1 7 1 6 2 8”创建:
我想遍历网格,只打印对角线左侧和/或右侧的值,然后从新找到的值中打印它们的对角线。
示例网格的一些示例路线(上面标有 * 的一条):
index[0][0]: [6,8,1,6], [6,8,1,6], [6,8,1,8]
index[0][1]: [4,3,5,1], [4,3,5,2], [4,9,5,2], [4,9,5,1], [4,9,7,2] *
路线将输出为:
4351, 4352, 4952 etc.
基本上,我想在网格中以“之字形”的方式找到所有路线。
我目前的代码如下:
public static void main(String[] args)
{
int s = 4; //For demo purposes
int k = 0;
String grid[][] = new String[s][s]; //Grid will always be n x n
Scanner sc = new Scanner(System.in); //Handles a whitespace delimited string
String[] in = sc.nextLine().split("\\s+");
for (int i = 0; i < size; i++) { //Creates the grid
for (int j = 0; j < size; j++) {
grid[i][j] = in[k];
k++;
}
}
for (int j = 0; j < size; j++) { //Route finder
for (int i = 0; i < size; i++) {
//find a diagonal value and append the value to the route
}
//Print the route integers for this specific route
}
}
我将如何在矩阵中找到这些路线?还可以解决万能的 IndexOutOfBounds 错误吗?
【问题讨论】:
-
如果您在循环中
return,您将没有机会找到任何替代路线。 -
@ScottHunter 编辑了代码 sn-p 以改为读取打印。
-
@ScottHunter 我在第二个循环中有边界检查器,但省略了它们以允许其他用户的任何想法解决它。循环本身不会给出边界错误,但会检查对角线值是否存在。执行
grid[i+1][j+1]和grid[i+1][j-1]会直接在运行时出错,因为后者会尝试检查-1 索引列。 This 是我指的 IndexOutOfBounds 错误。如果不清楚,请致歉。
标签: java arrays for-loop matrix indexing