螺旋化

May 06, 2018

原题如下

Your task, is to create a NxN spiral with a given size.

For example, spiral with size 5 should look like this:

00000
....0
000.0
0...0
00000

and with the size 10:

0000000000
.........0
00000000.0
0......0.0
0.0000.0.0
0.0..0.0.0
0.0....0.0
0.000000.0
0........0
0000000000

Return value should contain array of arrays, of 0 and 1, for example for given size 5 result should be:

[
  [1, 1, 1, 1, 1],
  [0, 0, 0, 0, 1],
  [1, 1, 1, 0, 1],
  [1, 0, 0, 0, 1],
  [1, 1, 1, 1, 1]
]

Because of the edge-cases for tiny spirals, the size will be at least 5.

General rule-of-a-thumb is, that the snake made with ‘1’ cannot touch to itself.

这个费了半天时间弄了个超级复杂的解答,但是看到最佳答案的时候我都蒙了

function spiralize(size) {
  if (size == 2)
    return [
      [1, 1],
      [0, 1],
    ]
  if (size == 3)
    return [
      [1, 1, 1],
      [0, 0, 1],
      [1, 1, 1],
    ]
  var base = spiralize(size - 2)
  var res = [[], []]
  for (var i = 0; i < size; i++) {
    res[0].push(1)
    res[1].push(0)
  }
  res[1][size - 1] = 1
  for (var i = size - 3; i >= 0; i--) {
    res.push(base[i].reverse().concat([0, 1]))
  }
  res[size - 1][size - 2] = 1
  return res
}

递归来做,想都没往这个方向想

留下一个其他人的回复

Woah! it’s an art! :)


目录