inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

it 취업을 위한 알고리즘 문제풀이 입문 (with C/C++) : 코딩테스트 대비

89. 토마토(BFS 활용)

시간 초과가 나고 있습니다 선생님 어느 부분에서 효율화가 필요할까요??

174

celestial_

작성한 질문수 72

0

선생님, 안녕하세요? 늘 좋은 강의 감사드립니다. 

본 문제 코드를 bfs로 풀었는데,

4 5 예제에서 오류가 발생하고 있습니다. 

제 코드 상에서 어느 부분이 효율이 떨어지고 있는지 

궁금합니다. 한번 제 코드를 봐주시면 대단히 감사하겠습니다. 

늘 좋은 영상 감사드립니다.

#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<queue>
#include<algorithm>
#include<vector>

using namespace std;

int TomatoBox[1000][1000];
int visited[1000][1000];
int n, m;
queue<pair < pair<int, int>, int> >Q;

int dx[4] = { -1,1,0,0 };
int dy[4] = { 0,0,-1,1 };
void BFS(pair< pair<int, int>, int> vertex) {
	pair< pair<int, int>, int> temp;

	while (!Q.empty()) {
		
		temp.first.first = Q.front().first.first;
		temp.first.second = Q.front().first.second;
		temp.second = Q.front().second;
		//temp.second++;
		Q.pop();
		for (int i = 0; i < 4; i++) {
			int x = temp.first.first + dx[i];
			int y = temp.first.second + dy[i];
			int v = temp.second;
			
			if (x < 0 || y < 0 || x >= n || y >= m) {

				continue;
			}
			if (TomatoBox[x][y] == 1 || TomatoBox[x][y] == -1) { continue; }
			//토마토가 익지 않았고 아직 방문을 하지 않았다면
			if (visited[x][y] == 0 && TomatoBox[x][y] == 0) {
				v++;
				
				pair< pair<int, int>, int>next;
				visited[x][y] = 1;
				TomatoBox[x][y] = 1;
				next.first.first = x;
				next.first.second = y;
				next.second = v;

				Q.push(next);
			}
			else { return; }
		}

	}
	int flag = 0;
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < m; j++) {
			if (TomatoBox[i][j] == 0) { flag = 1; break; }
			else { continue; }
		}
	}
	if (flag == 0) {
		printf("%d ", temp.second);
	}
	else {
		printf("-1");
	}

}

int main() {
	ios_base::sync_with_stdio(false);
	/*scanf("%d %d", &m, &n);*/
	cin >> m >> n;
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < m; j++) {

			//scanf("%d", &TomatoBox[i][j]);
			cin >> TomatoBox[i][j];
		}
	}
	

	//시작점의 갯수를 파악합니다. 
	int startcount = 0;
	//pair <pair<int, int>, int> start;
	vector< pair <pair<int, int>, int> > startpoint(1000);
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < m; j++) {
			if (TomatoBox[i][j] == 1) {

				startcount++;
				//printf("현재 시작점의 개수 : %d \n", startcount);
				startpoint[startcount].first.first = i;
				//printf("해당 시작점의 x좌표 : %d \n", startpoint[startcount].first.first);
				startpoint[startcount].first.second = j;
				//printf("해당 시작점의 y좌표 : %d \n", startpoint[startcount].first.second);
				startpoint[startcount].second = 0;
				//printf("해당 시작점에서의 움직임 계수 : %d \n", startpoint[startcount].second);
				visited[startpoint[startcount].first.first][startpoint[startcount].first.second] = 1;
				startpoint[startcount];
				Q.push(startpoint[startcount]);

				
				Q.push(startpoint[startcount]);
				
			}
		}

	}
	BFS(startpoint[1]);
	return 0;
}

C++ 코테 준비 같이 해요!

답변 1

0

김태원

안녕하세요^^

TomatoBox의 크기가 1000*1000입니다. 최악의 경우 1의 개수가 1,000,000개까지 들어올 수 있다는 겁니다.

startpoint의 크기인 1000은 너무 작습니다.

테스트 케이스 질문

0

371

1

병합정렬 시간복잡도 질문

0

461

1

41.연속된 자연수의 합 문제풀이에서 수학적인 원리를 모르고 있습니다.

0

1341

2

질문드립니다.

0

374

1

질문드립니다!

0

428

1

dev 프로그램 질문

0

273

1

문제가 이해가 안되요

0

374

1

4번 나이차이 문제 접근법 질문 드립니다.

0

305

1

source file not compiled

0

1033

3

59번 질문드립니다.

0

370

1

25번 문제 질문

0

346

1

4. 나이차이 문제 질문입니다.

0

368

1

90번 라이언 킹 심바 1번 테스트 케이스

0

468

1

71번 문제 전역 변수 질문 있습니다

0

357

1

75번, 79번 priority_queue관련

1

353

1

75.최대 수입 스케줄

0

394

2

복면산 정답의 수

0

428

1

테스트 케이스에 대해서

0

443

1

수업 내용 질문입니다!

1

229

1

풀어보면 좋은 문제 목록 - 2580 스토쿠 DFS 질문입니다!!

0

818

2

12. 플로이드-와샬(그래프 최단거리) . 27:25초

0

252

1

다른 풀이 방식

0

314

1

크루스칼 vs 프림

0

304

1

숫자 총개수 small 질문있습니다.

0

234

1