티스토리 뷰
사용언어 : C++
BFS 사용하여서, 해결하면 된다. 다만 여기서 주의할 점은 날짜별로 체크하기 때문에, q.size만큼 다 돌린후 날짜 + 1을 하였다.
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;
#define MAXR 1001
vector<vector<int>> arr;
int visit[MAXR][MAXR] = { 0 };
int coun;
queue<pair<int, int>> q;
void BFS();
int check[4][2] = { {1,0},{-1,0},{0,1},{0,-1} };
int N, M;
bool compare(int i, int j) {
return j < i;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> N >> M;
for (int i = 0; i < M; ++i) {
vector<int> num;
int a;
for (int j = 0; j < N; j++) {
cin >> a;
num.push_back(a);
if (a == 1) {
q.push(pair<int, int>(i, j));
visit[i][j] = 1;
}
else if (a == -1)
visit[i][j] = 1;
}
arr.push_back(num);
}
BFS();
bool type = false;
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
if (visit[i][j] == 0) {
type = true;
break;
}
}
if (type)
break;
}
if (type)
cout << "-1" << "\n";
else
cout << coun-1 << "\n";
}
void BFS() {
while (!q.empty()) {
int n = q.size();
for (int i = 0; i < n; i++) {
pair<int, int> a = q.front();
q.pop();
for (int j = 0; j < 4; j++) {
int ny = a.first + check[j][0];
int nx = a.second + check[j][1];
if ((nx >= 0 && nx < N) && (ny >= 0 && ny < M)){
if (visit[ny][nx] == 0) {
q.push(pair<int, int>(ny, nx));
visit[ny][nx] = 1;
arr[ny][nx] = 1;
}
}
}
}
coun++;
}
}
'자료구조 및 알고리즘 > 문제풀이' 카테고리의 다른 글
백준 C++ 9148번 ) 신나는 함수 실행 (0) | 2022.07.16 |
---|---|
백준 C++ 24415번) 알고리즘 수업 (0) | 2022.07.16 |
백준 C++ 27779번) DFS 깊이 우선 탐색 (0) | 2022.06.17 |
프로그래머스 C++ ) 전화번호 목록 (0) | 2022.06.01 |
백준 C++ 10815번) 숫자카드 (0) | 2022.05.31 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 백준
- 스레드풀
- 지뢰찾기
- BFS
- 정보보안
- 인제대학교
- 링크드 리스트
- c++
- 알고리즘
- 시스템보안
- 보안
- 멀티쓰레드
- 레지스터
- queue
- 워셜알고리즘
- 더블버퍼링
- 컨퍼런스
- 자료구조
- Dreamhack
- 개발
- 야경
- 고양이
- Select모델
- 학교
- 드림핵
- STL
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |
글 보관함