#include <stdio.h> #include <iostream> #include <queue> #include <vector> #include <algorithm> using namespace std; int map[310][310]; int T; int len; int startX, startY, endX, endY; queue<pair<int, int>> q; int visited[310][310]; int dx[8] = {-1, -2, -2, -1, 1, 2, 2, 1}; int dy[8] = {-2, -1, 1, 2, 2, 1, -1, -2}; void init() { for(int i = 0; i < len; i++) { for(int j = 0; j < len; j++) { visited[i][j] = 0; } } } int safe(int x, int y) { if(x >= 0 && x < len && y >= 0 && y < len) { return 1; } else { return 0; } } void BFS() { visited[startX][startY] = 1; q.push({startX, startY}); while(!q.empty()) { int x = q.front().first; int y = q.front().second; q.pop(); for(int i = 0; i < 8; i++) { int xpos = x+dx[i]; int ypos = y+dy[i]; if(safe(xpos, ypos) == 1 && visited[xpos][ypos] == 0) { visited[xpos][ypos] = visited[x][y] + 1; q.push({xpos, ypos}); } } } } int main(void) { // freopen("B7562_input.txt", "r", stdin); scanf("%d", &T); for(int n = 1; n <= T; n++) { cin >> len; cin >> startX >> startY >> endX >> endY; BFS(); cout << visited[endX][endY]-1 << endl; init(); } return 0; } | cs |
'Baekjoon > BFS' 카테고리의 다른 글
[백준 2468] 안전영역 (BFS) (C/C++) (0) | 2019.12.04 |
---|---|
[백준 9177] 단어 섞기 (DFS/BFS) (C/C++) (★★) (0) | 2019.12.04 |
[백준 2251] 물통 (BFS) (C/C++) (0) | 2019.12.02 |
[백준 5014] 스타트 링크 (BFS) (C/C++) (0) | 2019.12.02 |
[백준 1697] 숨바꼭질 (BFS) (C/C++) (0) | 2019.12.02 |