Looping XYZ from the center
I have a three dimensional array which I want to fill in with values in C#. By looping one dimension at a time it will start at one corner, and work in rows until it finishes at the opposite corner.
Standard loop:
for (int x = 0; x < 10; x++)
for (int y = 0; y < 10; y++)
for (int z = 0; z < 10; z++)
{
// fill value
开发者_如何学JAVA }
I want to loop the same values, but start at the center of the array, and slowly work my way outward, so that if I look at the array in 3D space as it's being filled, it will slowly grow as a ball (or cube) from the middle.
Any good ideas on how I can do this? Ideas for both filling a cube form, and filling as a sphere (ie. closest distance to middle) would be great!
You may use something like BFS
C-style pseudocode, not C#:
class Point{int x,y,z;};
queue<Point> q;
bool used[100][100][100]; //all false. true when add point to queue
Point vectors[]={(0,0,1),(0,0,-1),(0,1,0),(0,-1,0),(1,0,0),(-1,0,0)}
q.push(Point(50,50,50)); //start point
used[50][50][50]=true;
while(!q.empty()){
Point cur=q.front();
//use cur;
q.pop();
for(i=0;i<6;++i){
if(!used[cur+vectors[i]] && (cur+vectors[i] is in our diapason)){
q.push(cur+vectors[i]);
used[cur+vectors[i]]=true;
}
}
}
It will fill area by Manhettan distance. So it will cube, but corner to top and bottom
Also you may use this naive solution(pseudocode too):
Point points[];
for (int x = 0; x < 10; x++)
for (int y = 0; y < 10; y++)
for (int z = 0; z < 10; z++)
{
add to point array
}
sort points[] by function r() (if r(a)<r(b) then a before b)
loop points here
r(a)=sqrt((a.x-5)^2+(a.y-5)^2+(a.z-5)^2) for ball
r(a)=max(abs(a.x-5),abs(a.y-5),abs(a.z)-5) for cube
精彩评论