Little Jay

[C++] 백준 13565번 - 침투 본문

알고리즘/BOJ

[C++] 백준 13565번 - 침투

Jay, Lee 2022. 5. 3. 17:39

입력받는것을 계속 int로 받다가 실패했다.

띄어쓰기가 없는 것은 char이나 string으로 받아야 하는 것에 유의하자.

n-1일때 return true 해야하는데 m-1로 계속 써서 실패했다.

항상 조건을 잘 보도록 하자.

#include <bits/stdc++.h>
#define endl '\n'
using namespace std;

int n, m;
int board[1005][1005];
bool visited[1005][1005];
const int dx[4] = { 1, -1, 0, 0 };
const int dy[4] = { 0, 0, 1, -1 };

bool bfs(int y, int x) {
	visited[y][x] = true;
	queue<pair<int, int>> q;
	q.push({ y, x });
	while (!q.empty()) {
		auto current = q.front(); q.pop();
		if (current.first == n - 1) 
			return true;

		for (int dir = 0; dir < 4; dir++) {
			int ny = current.first + dy[dir];
			int nx = current.second + dx[dir];

			if (nx < 0 || nx >= m || ny < 0 || ny >= n) continue;

			if (!visited[ny][nx] && board[ny][nx] == 0) {
				visited[ny][nx] = true;
				q.push({ ny, nx });
			}
		}
	}
	return false;
}

int main() {

	ios::sync_with_stdio(false);
	cin.tie(0); cout.tie(0);

	cin >> n >> m;
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < m; j++) {
			char x; cin >> x;
			board[i][j] = x - '0';
		}
	}

	bool ans = false;
	for (int i = 0; i < m; i++) {
		if (board[0][i] == 0)
			ans = bfs(0, i);
		if (ans == true) break;
	}

	if (ans) cout << "YES" << endl;
	else cout << "NO" << endl;
	return 0;
}
Comments