# 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

```.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}snail = function (array) {2  const n = array[0].length3
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 < n8  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] = true16  }17
18  for (let row = 0, col = 0; n > 0; ) {19    if (canGoRight(row, col)) {20      while (canGoRight(row, col)) visit(row, col++)21      continue22    }23
24    if (canGoDown(row, col)) {25      while (canGoDown(row, col)) visit(row++, col)26      continue27    }28
29    if (canGoLeft(row, col)) {30      while (canGoLeft(row, col)) visit(row, col--)31      continue32    }33
34    if (canGoUp(row, col)) {35      while (canGoUp(row, col)) visit(row--, col)36      continue37    }38
39    // final cell40    visit(row, col)41
42    break43  }44
45  return res46}```

codewars

array

## 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

Search Posts