문제접근
•
테스트 케이스마다 board 벡터 초기화
•
8방위 배열 설정
•
bfs 돌면서 현재 좌표가 타겟 좌표이면 종료
•
visited 배열대신 -1로 초기화하고 방문할때마다 +1씩 하여 -1이 아니면 방문한것으로 처리
놓쳤던 부분
코드
2420 KB
28 ms
#include <iostream>
#include <queue>
#include <utility>
#include <vector>
using namespace std;
int dx[8] = {1, 2, 2, 1, -1, -2, -2, -1};
int dy[8] = {-2, -1, 1, 2, 2, 1, -1, -2};
int l;
vector<vector<int> > board;
int targetRow, targetCol;
void bfs(int row, int col) {
queue<pair<int, int> > q;
q.push({row, col});
board[row][col] = 0;
while (!q.empty()) {
int currentRow = q.front().first;
int currentCol = q.front().second;
if (currentRow == targetRow && currentCol == targetCol) {
cout << board[currentRow][currentCol] << "\n";
return ;
}
q.pop();
for (int i = 0; i < 8; i++) {
int nextRow = currentRow + dy[i];
int nextCol = currentCol + dx[i];
if (nextRow < 0 || nextRow >= l || nextCol < 0 || nextCol >= l)
continue ;
if (board[nextRow][nextCol] != -1)
continue ;
board[nextRow][nextCol] = board[currentRow][currentCol] + 1;
q.push({nextRow, nextCol});
}
}
}
int main(void) {
int t;
int startRow, startCol;
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> t;
for (int i = 0; i < t; i++) {
cin >> l;
board.resize(l, vector<int>(l));
fill(board.begin(), board.end(), vector<int>(l, -1));
cin >> startRow >> startCol;
cin >> targetRow >> targetCol;
bfs(startRow, startCol);
}
return (0);
}
C++
복사