알고리즘/프로그래머스
[C++] 프로그래머스 리코쳇 로봇
이영재의오른발
2023. 3. 22. 13:53
반응형
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 60 61 62 63 64 65 66 67 68 69 70 71 | #include <string> #include <vector> #include <queue> #include <iostream> using namespace std; int dx[] = {0,0,-1,1}; int dy[] = {-1,1,0,0}; int n,m; int answer = -1; bool check[101][101]; struct b { int x; int y; int cnt; }; void bfs(int x_tmp, int y_tmp, vector<string> board) { queue<b> q; q.push({x_tmp,y_tmp,0}); while(!q.empty()) { int x = q.front().x; int y = q.front().y; int cnt = q.front().cnt; check[x][y] = true; if(board[x][y] == 'G') { answer = cnt; break; } q.pop(); for(int i=0; i<4; i++) { int x1 = x; int y1 = y; while(1) { int nx = x1 + dx[i]; int ny = y1 + dy[i]; if(nx < 0 || ny < 0 || nx >=n || ny >= m || board[nx][ny] == 'D') { if(!check[x1][y1]) { q.push({x1,y1,cnt+1}); } break; } else { x1 = nx; y1 = ny; } } } } } int solution(vector<string> board) { n = board.size(); m = board[0].size(); for(int i=0; i<n; i++) { for(int j=0; j<m; j++) { if(board[i][j] == 'R') { bfs(i,j,board); } } } return answer; } | cs |
BFS + 구현
while 문을 이용해 장애물, 맨끝에 부딪힐때까지 이동하는 코드만 작성하면 쉽게 풀리는 문제
정답률이 낮은 이유는 구현에서 애를먹어서 그런게 아닐까??
728x90
반응형