且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java的创建螺旋

更新时间:2023-11-18 09:14:46

您不必pre-充满10:零的作品一样好

You do not need to pre-fill with 10: zero works just as well.

我觉得解决螺旋***的办法是想你怎么做手工:开始在一个角落里,去水平,直到你打不为零或阵列的边缘。然后右转。当停止当前一些去通过N *ñ。

I think the best approach to solving the spiral is to think of how you do it manually: start in a corner, and go horizontally until you hit non-zero or an edge of the array. Then you turn right. Stop when the current number goes past N*N.

现在让我们来看看什么是算法的每个部分的含义:

Now let's look at what each part of the algorithm means:

  • 开始在角落机构将x = 0和Y = 0。
  • 去在一条直线上装置X = X + DX,Y = Y + DY,其中DX任或镝是零,和dy或dx为1或-1。
  • 在谈到DX分配到Dy和-dy到DX正确的方式。

下面是如何看起来在code:

Here is how it looks in the code:

int current = 1;
// Start in the corner
int x = 0, y = 0, dx = 1, dy = 0;
while (current <= N*N) {
    // Go in a straight line
    spiral[x][y] = current++;
    int nx = x + dx, ny = y + dy;
    // When you hit the edge...
    if (nx < 0 || nx == N || ny < 0 || ny == N || spiral[nx][ny] != 0) {
        // ...turn right
        int t = dy;
        dy = dx;
        dx = -t;
    }
    x += dx;
    y += dy;
}