[Codewars] Snail

Snail

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <vector>
using namespace std;
std::vector<int> snail(const std::vector<std::vector<int>> &snail_map) {
int n = snail_map.size(), m = snail_map[0].size();
if(!n or !m) return {};
vector<vector<bool>> vis(n, vector<bool>(m));
vector<int> res;
int dy[4]{0,1,0,-1}, dx[4]{1,0,-1,0}, d = 0, y = 0, x = 0;
auto go = [&]() {
for(int i = 0; i < 4; i++) {
int ny = y + dy[d], nx = x + dx[d];
if(0 <= ny and ny < n and 0 <= nx and nx < m and !vis[ny][nx]) {
y = ny, x = nx;
return true;
}
d = (d + 1) % 4;
}
return false;
};
do {
res.push_back(snail_map[y][x]);
vis[y][x] = true;
} while(go());
return res;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/05/05/PS/Codewars/snail/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.