如果我有一个二维数组,如:
boolean[][] map = new boolean[50][50];
如何仅在循环中将布尔的外边缘设置为true?
因此,对于以下数组:
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
你会:
1 1 1 1 1 1
1 0 0 0 0 1
1 0 0 0 0 1
1 0 0 0 0 1
1 1 1 1 1 1
我是编程新手,我一直在努力让这个工作起作用?
我想可能使用2个循环,如:
for(int i = 0; i < map.length; i++)
{
map[i][0] = true;
map[i][map[0].length] = true;
}
for(int i = 0; i < map[0].length; i++)
{
map[0][i] = true;
map[map.length][i] = true;
}
但说实话,我不确定这是否是正确的做法?
答案 0 :(得分:3)
for( int i = 0; i<maxx; i++)
{
for( int j = 0; j<maxy; j++)
{
if( i==0 || i == maxx-1 || j == 0 || j == maxy-1 )
{
//Write 1
}
else
{
//Write 0
}
}
}
这可能不是最好的代码,但它很容易演示如何实现它:
在所有领域写点东西。
如果字段是:
写 1 ,否则写 0 。
问题是,当它位于顶部还是底部时?
当行索引( i )为0或最高可能时。
列索引的计数相同( j )。
答案 1 :(得分:1)
for( int i = 0; i<50; i++)
{
map[i][0] = 1;
map[i][49] = 1;
map[0][i] = 1;
map[49][i] = 1;
}
答案 2 :(得分:1)
我假设结构已经用0初始化。
integer max = 50;
boolean[][] map = new boolean[max][max];
for ( integer x=0;x<max;x++) {
map[0,x] =1;
map[max-1,x] =1;
map[x,0] =1;
map[max-1,x] =1;
}
问题:这不止一次初始化角落。
答案 3 :(得分:0)
在Java中:
int firstRow = 0;
int lastRow = map.length - 1;
int width = map[0].length;
for (int i=0; i<width; i++) {
map[firstRow][i] = true;
}
System.arrayCopy (map[firstRow], 0, map[lastRow], 0, width);
int lastColumn = width - 1;
for (int i=1; i<lastRow; i++) {
map[i][0] = map[i][lastColumn] = true;
}
答案 4 :(得分:0)
这当然受限于你必须做的写入次数,即O(n),其中n是矩阵的边长,假设矩阵是正方形。
您当然可以简化代码以仅触及外部元素:
for i in xrange(0, n - 1):
matrix[0][i] = true
matrix[i][-1] = true
matrix[-1][-(i + 1)] = true
matrix[-(i + 1)][0] = true
这对循环的每次迭代执行四次写入。我认为我现在正确地进行了索引,想法是按照这个顺序进行写入,对于n = 4的情况(令人惊叹的ASCII图形道歉):
0120
2 1
1 2
0210
所以,你可以看到每一方只从0到n - 2,包括在内。这在Python中表示为for i in xrange(0, n -1)
。
答案 5 :(得分:0)
在Python中很容易
X=10
Y=5
m=[[1]*X]+[[1]+[0]*(X-2)+[1]]*(Y-2)+[[1]*X]
for row in m:
print row
输出:
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1]
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1]
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
以下是细分
[1]*X # gives us a list of X 1's [1,1,1,1,1,1,1,1,1,1] in this case
[0]*(X-2) # gives us a list of (X-2) 0's [0,0,0,0,0,0,0,0] in this case
所以
[[1]*x] # gives us an 1 by X array [[1,1,1,1,1,1,1,1,1,1]]
[[1]+[0]*(X-2)+[1]] # gives a 1 by X array [[1,0,0,0,0,0,0,0,0,1]]
我们将上面的数组相乘以得到Y-2相同的线
然后在底部添加另一行1的