1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| int Solution::knight(int A, int B, int C, int D, int E, int F) { vector<vector<int>> vis(A, vector<int>(B)); queue<pair<int,int>> q; q.push({C-1,D-1}); vis[C-1][D-1] = 1; int dy[8]{-1,-2,-2,-1,1,2,2,1}, dx[8]{-2,-1,1,2,2,1,-1,-2}; while(q.size() and vis[E-1][F-1] == 0) { auto [y,x] = q.front(); q.pop(); for(int i = 0; i < 8; i++) { int ny = y + dy[i], nx = x + dx[i]; if(0 <= ny and ny < A and 0 <= nx and nx < B and vis[ny][nx] == 0) { vis[ny][nx] = vis[y][x] + 1; q.push({ny,nx}); } } } return vis[E-1][F-1] - 1; }
|