백준 16948 c++

magicdrill·2024년 3월 21일
0

백준 문제풀이

목록 보기
184/654

백준 16948 c++

간단한 BFS 문제인데 q_size를 실시간으로 구하게 잘못 코드를 적어서 고치느라 시간이 오래 걸렸다.

#include <iostream>
#include <queue>
#include <vector>

using namespace std;

int N;
//vector<vector<int>> chess_board;
vector<vector<bool>> visited;
int r1, c1, r2, c2;
vector<pair<int, int>>direction{ {-2, -1},{-2, 1}, {0, -2}, {0, 2}, {2, -1}, {2, 1} };

void input_board()
{
	cin >> N;
	//chess_board.resize(N, vector<int>(N, 0));
	visited.resize(N, vector<bool>(N, false));
	cin >> r1 >> c1 >> r2 >> c2;

	return;
}

int BFS(int r1, int c1, int r2, int c2)
{
	int i, j, direct = direction.size(), count = 0, q_size;
	int current_x, current_y;
	int next_x, next_y;
	queue <vector<int>> q;

	//r이 x값, c가 y값
	q.push({ r1, c1 });
	visited[c1][r1] = true;
	while (!q.empty())
	{
		q_size = q.size();
		for (j = 0; j < q_size; j++)
		{
			current_x = q.front()[0];
			current_y = q.front()[1];
			q.pop();
			for (i = 0; i < direct; i++)
			{
				next_x = current_x + direction[i].first;
				next_y = current_y + direction[i].second;
				if ((next_x >= 0 && next_x < N) && (next_y >= 0 && next_y < N) && visited[next_y][next_x] == false)
				{
					visited[next_y][next_x] = true;
					q.push({ next_x, next_y });
				}
			}
		}
		count++;
		if (visited[c2][r2] == true)
		{
			return count;
		}
	}

	return -1;
}

void find_answer()
{
	cout << BFS(r1, c1, r2, c2) << "\n";

	return;
}

int main(void)
{
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);

	input_board();
	find_answer();

	return 0;
}

0개의 댓글