/* 백준 7562 나이트의 이동 (200828) <시뮬> */
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <iostream>
#include <vector>
#include <algorithm>
#include <math.h>
#include <queue>
using namespace std;
bool inRange(int row, int col, int size) {
if (row >= 0 && row <= size - 1 && col >= 0 && col <= size - 1)
return true;
else
return false;
}
int main() {
int testCase;
scanf("%d", &testCase);
for (int tc = 0; tc < testCase; tc++) {
int l;
scanf("%d", &l);
int nightRow, nightCol, finalRow, finalCol;
scanf("%d %d", &nightRow, &nightCol);
scanf("%d %d", &finalRow, &finalCol);
queue<pair<int, int>> q;
vector<vector<bool>> discover(l, vector<bool>(l, false));
vector<vector<int>> distance(l, vector<int>(l)); //거리 적어두는 배열
q.push(make_pair(nightRow, nightCol));
discover[nightRow][nightCol] = true;
while (!q.empty()) {
int currentRow, currentCol, currentDis;
currentRow = q.front().first;
currentCol = q.front().second;
currentDis = distance[currentRow][currentCol];
if (currentRow == finalRow && currentCol == finalCol) //도착하면
break;
q.pop();
for (int i = -2; i <= 2; i++) {
for (int j = -2; j <= 2; j++) {
if (i == 0 || j == 0 || (abs(i) == 1 && abs(j) == 1) || (abs(i) == 2 && abs(j) == 2)) //나이트로 못가는 곳이면 continue
continue;
//다음에 갈 row, col
int thereRow = currentRow+i;
int thereCol = currentCol+j;
if (inRange(thereRow, thereCol, l)) {
if (!discover[thereRow][thereCol]) {
q.push(make_pair(thereRow, thereCol));
discover[thereRow][thereCol] = true;
distance[thereRow][thereCol] = currentDis + 1;
}
}
}
}
}
printf("%d\n", distance[finalRow][finalCol]);
}
return 0;
}
1. 고칠 점
나이트로 갈 수 있는 칸을 구할 때 저렇게 이중 for문을 도는 것보다
dRow[8] = [-2, -2, -1, -1, 1, 1, 2, 2];
dCol[8] = [-1, 1, -2, 2, -2, 2, -1, 1];
for(int i=0;i<8;i++){
int thereRow = currentRow + dRow[i];
int thereCol = currentCol + dCol[i];
}
로 하는게 더 깔끔할 듯
'Baekjoon' 카테고리의 다른 글
[#12100] 2048(Easy) (0) | 2020.10.11 |
---|---|
[#3190] 뱀 (0) | 2020.10.10 |
[#16234] 인구 이동 (0) | 2020.08.27 |
[#15683] 감시 (0) | 2020.08.26 |
[#11657] 타임머신 (0) | 2020.04.01 |