CodeWars: Snail Solution

Keep going in a way

Approach

Keep going in one direction at a time, with the order:

  • right
  • down
  • left
  • up
  • ..then repeat

Implementation

1snail = function (array) {
2 const n = array[0].length
3
4 const visited = Array.from({ length: n }, _ => Array(n).fill(false))
5 const res = []
6
7 const valid = (row, col) => 0 <= row && row < n && 0 <= col && col < n
8 const canGoUp = (row, col) => valid(row - 1, col) && !visited[row - 1][col]
9 const canGoDown = (row, col) => valid(row + 1, col) && !visited[row + 1][col]
10 const canGoLeft = (row, col) => valid(row, col - 1) && !visited[row][col - 1]
11 const canGoRight = (row, col) => valid(row, col + 1) && !visited[row][col + 1]
12
13 const visit = (row, col) => {
14 res.push(array[row][col])
15 visited[row][col] = true
16 }
17
18 for (let row = 0, col = 0; n > 0; ) {
19 if (canGoRight(row, col)) {
20 while (canGoRight(row, col)) visit(row, col++)
21 continue
22 }
23
24 if (canGoDown(row, col)) {
25 while (canGoDown(row, col)) visit(row++, col)
26 continue
27 }
28
29 if (canGoLeft(row, col)) {
30 while (canGoLeft(row, col)) visit(row, col--)
31 continue
32 }
33
34 if (canGoUp(row, col)) {
35 while (canGoUp(row, col)) visit(row--, col)
36 continue
37 }
38
39 // final cell
40 visit(row, col)
41
42 break
43 }
44
45 return res
46}

Comments

Loading comments...

Tags

codewars

array

Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.

Next Post

LeetCode: Reverse Words in a String III

Sep 15, 2021

One line

Previous Post

LeetCode: Two Sum II - Input array is sorted

Sep 14, 2021

If trying to explain takes time, go on

HoningJS

Search Posts