我有一個二維數組,可以通過任何整數N動態創建。最初,我需要將數組中的所有值設置爲表示「未初始化」的值,我使用數字「-1」。但是,我想將這個二維數組轉換爲一維數組,並將每個值賦予等於它在新的一維數組中的索引。如何將二維數組轉換爲一維數組作爲索引?
public class Percolation {
private int[][] id;
private int[] array1D;
private int blocked = -1; //a number that doesn't exist in the array
// create N-by-N grid, with all sites blocked
public Percolation(int N){
id = new int[N][N];
for (int k = 0; k < N; k++)
{ for (int i = 0; i < N; i++) id[k][i] = blocked; }
}
// open site (row i, column j) if it is not already
public void open(int i, int j){
}
在open方法中,它應該將給定索引處的值更改爲1D數組中的對應索引。例如:
[-1] [-1]
[-1] [-1]
將隨後成爲:
[0] [1 ] [2] [3]
不幸的是,由於這是功課,我不確定如何分享網格大小「N」能夠創建一個索引作爲值的新的一維數組。
關於你的最後一段:你用'id.length'在你的類中得到網格大小'N'。 – halex
@halex哇謝謝,這正是我需要的全部 – Ci3
我會讓它成爲答案,並希望你接受它:) – halex