Algorithm/graph

[백준] 알고리즘 7562번 - 나이트의 이동문제

낭강 2021. 2. 3. 02:24

#include <bits/stdc++.h>
using namespace std;
int dx[8] = {-2,-2,-1,1,2,2,1,-1};
int dy[8] = {-1,1,2,2,1,-1,-2,-2};
int check[301][301];
queue<pair<int,int>> qu;
int l;

void bfs(int x,int y) {
	 
	while (!qu.empty()) {
		int first = qu.front().first;
		int se = qu.front().second;
		qu.pop();
		for (int i = 0; i < 8; i++) {
			int cx = first + dx[i];
			int cy = se + dy[i];
			if (cx<0 || cx>=l || cy<0 || cy>=l) continue;
			if (check[cx][cy] == 0) {
				check[cx][cy] = check[first][se]+1;
				qu.push(make_pair(cx, cy));
			}
		}
	}
}
int main(){
   ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
   int T;
   cin >> T;
   while (T--) {
	   int nx, ny, mx, my;
	   cin >> l >> nx >> ny >> mx >> my;
	   check[nx][ny] = 1;
	   qu.push(make_pair(nx, ny));
	   bfs(nx,ny);
	   cout << check[mx][my]-1<<"\n";
	   for (int i = 0; i < l; i++) {
		   for(int j=0;j<l;j++) check[i][j]=0;
	   }
   } 
}

BFS를 이용하여 문제를 해결하였습니다.

DX, DY값만 이해하여 설정해두면 쉽게 해결할수있습니다.

TIP

BFS(시작점,시작점)

출력 -> 종점