Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 문자열&연산자
- Server
- 제로베이스 프론트엔드 스쿨
- dfs
- leetcode
- 구현
- 코딩테스트
- 백트래킹
- MemoryBarrier
- 구조체
- 코딩테스트 스터디
- 알고리즘
- N과 M(2)
- c#
- map
- 멀티스레드
- C++
- 완전탐색
- 서버
- socket
- 제로베이스
- 자바스크립트
- 메모리 배리어
- 프론트엔드 스쿨
- JavaScript
- 프로그래머스
- 백준
- React
- Algorithm
- BFS
Archives
- Today
- Total
Written
프로그래머스 / 숫자 변환하기 / C++ 본문
처음엔 DFS로 완전탐색 방식으로 구현해봤는데, 테스트케이스 절반에서 시간초과가 나서 BFS로 바꾸었더니
시간초과 없이 전부 맞출 수 있었습니다. 문제를 풀 때, BFS를 사용할 수 있으면 BFS가 높은 점수를 받기에는
더 좋은 것 같습니다.
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
|
#include <string>
#include <vector>
#include <climits>
#include <queue>
#include <algorithm>
using namespace std;
// DFS로 완전탐색때는 시간초과 났었기때문에 BFS로 다시 품
bool flag = false;
int total = INT_MAX;
int visited[1000001];
void BFS(int a, int b, int n)
{
int dx[3] = {2,3,n};
int start = a;
queue<pair<int,int>> Q;
Q.push({start,0});
visited[start] = 1;
while(!Q.empty())
{
auto cur = Q.front();
Q.pop();
if (cur.first == b)
{
flag = true;
if (cur.second < total)
total = cur.second;
}
for (int i=0;i<3;i++)
{
int next;
if (i==2)
next = cur.first + dx[i];
else
next = cur.first * dx[i];
if (next > b || visited[next] == 1)
continue;
visited[next] = 1;
Q.push({next,cur.second+1});
}
}
}
int solution(int x, int y, int n) {
BFS(x,y,n);
if (flag == false)
return -1;
return total;
}
|
cs |
'알고리즘 문제풀이' 카테고리의 다른 글
프로그래머스 / 테이블 해시 함수 / C++ (0) | 2023.08.31 |
---|---|
프로그래머스 / 마법의 엘리베이터 / C++ (0) | 2023.08.31 |
프로그래머스 / 호텔 대실 / C++ (0) | 2023.08.28 |
프로그래머스 / 무인도 여행 / C++ (0) | 2023.08.28 |
프로그래머스 / 광물 캐기 / C++ (0) | 2023.08.25 |
Comments