Untitled
unknown
plain_text
a year ago
2.8 kB
7
Indexable
#include <iostream> using namespace std; int T, N, M; char arr[105][105]; int visited[105][105]; int x1, y1, x2, y2; int spinX[8] = {-2, -2, -1, -1, 1, 1, 2, 2}; int spinY[8] = {-1, 1, -2, 2, -2, 2, -1, 1}; int X[8] = {-1, -1, -1, 0, 0, 1, 1, 1}; int Y[8] = {-1, 0, 1, -1, 1, -1, 0, 1}; class Queue{ private: int front, rear; int q[100000]; public: Queue(); void enQueue(int value); int deQueue(); void reset(); bool is_Empty(); }; Queue::Queue(){ front = rear = -1; } void Queue::enQueue(int value){ q[++rear] = value; } int Queue::deQueue(){ return q[++front]; } void Queue::reset(){ front = rear = -1; } bool Queue::is_Empty(){ if(front == rear) return true; return false; } Queue rQueue, cQueue; int main(){ freopen("input.txt", "rt", stdin); cin >> T; for(int tc = 1; tc <= T; tc++){ cin >> N >> M; for(int i = 0; i < N; i++){ for(int j = 0; j < M; j++){ visited[i][j] = 0; cin >> arr[i][j]; if(arr[i][j] == 'A'){ x1 = i; y1 = j; } if(arr[i][j] == 'B'){ x2 = i; y2 = j; } } } for(int i = 0; i < N; i++){ for(int j = 0; j < M; j++){ if(arr[i][j] == 'Z'){ visited[i][j] = -1; for(int k = 0; k < 8; k++){ int row = i + spinX[i]; int col = j + spinY[i]; if(row >= 0 && row < N && col >= 0 && col < M && visited[row][col] == 0){ visited[row][col] = -1; } } } } } rQueue.reset(); cQueue.reset(); visited[x1][y1] = 1; rQueue.enQueue(x1); cQueue.enQueue(y1); while(!rQueue.is_Empty()){ int cr = rQueue.deQueue(); int cc = cQueue.deQueue(); for(int i = 0; i < 8; i++){ int nr = cr + X[i]; int nc = cc + Y[i]; if(nr >= 0 && nr < N && nc >= 0 && nc < M && visited[nr][nc] == 0){ visited[nr][nc] = visited[cr][cc] + 1; rQueue.enQueue(nr); rQueue.enQueue(nc); } } } if(visited[x2][y2] == 0){ cout << -1 << endl; }else{ cout << visited[x2][y2] - 1 << endl; } } return 0; }
Editor is loading...