#include #include #include #include #include #include #include int dx[] = {1, 0, 0, -1}; int dy[] = {0, 1, -1, 0}; bool snakeOK(uint64_t shape, int len) { std::set > visited; visited.insert({0,0}); int x = 0; int y = 0; for(int i=1; i>= 2; x += dx[dir]; y += dy[dir]; if(visited.count({x, y})) return false; visited.insert({x,y}); } return true; } struct Snake { int r, c; uint64_t shape; Snake(int r, int c, uint64_t shape) : r(r), c(c), shape(shape) {}; Snake(uint64_t p) { c = p & 0xF; p >>= 4; r = p & 0XF; p >>= 4; shape = p; } uint64_t pack() const { uint64_t result = shape; result <<= 4; result += r; result <<= 4; result += c; return result; } }; int main() { int n, m; std::cin >> n >> m; std::vector grid(n*m); int headr = -1; int headc = -1; int appler = -1; int applec = -1; int len = 0; for(int i=0; i> c; grid[i*m+j] = c; if(c == 'A') { appler = i; applec = j; } else if(c == '0') { headr = i; headc = j; } else if(c != '.') { if('0' <= c && c <= '9') len = std::max(len, 1 + c - '0'); if('a' <= c && c <= 'f') len = std::max(len, 11 + c - 'a'); } } } uint64_t snakemask = 0; for(int i=1; i= n || nextc < 0 || nextc >= m) continue; if(grid[nextr*m+nextc] == nextseg) { shape |= (uint64_t(dir) << shift); shift += 2; curr = nextr; curc = nextc; break; } } } Snake starts{headr, headc, shape}; uint64_t hash = starts.pack(); std::unordered_map okshapes; std::unordered_set visited; std::deque q; q.push_front(hash); visited.insert(hash); while(!q.empty()) { uint64_t next = q.front(); q.pop_front(); Snake snake(next); if(snake.r == appler && snake.c == applec) { std::cout << "1" << std::endl; return 0; } for(int dir=0; dir<4; dir++) { int newr = snake.r + dx[dir]; int newc = snake.c + dy[dir]; if(newr < 0 || newr >= n || newc < 0 || newc >= m) continue; if(len > 1 && dir == (snake.shape & 0x3)) continue; int oppdir = 3-dir; uint64_t newshape = (snake.shape << 2) & snakemask; newshape |= oppdir; bool ok; auto it = okshapes.find(newshape); if(it == okshapes.end()) { // std::cout << "Trying snake: " << newr << " " << newc << " " << newshape << std::endl; ok = snakeOK(newshape, len); okshapes[newshape] = ok; } else ok = it->second; if(ok) { Snake newsnake{newr, newc, newshape}; uint64_t newhash = newsnake.pack(); if(!visited.count(newhash)) { visited.insert(newhash); q.push_front(newhash); } } } } std::cout << "0" << std::endl; }