-
[C++] 프로그래머스 무인도 여행알고리즘/프로그래머스 2023. 1. 27. 10:41반응형12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455#include <string>#include <vector>#include <algorithm>#include <queue>#include <iostream>using namespace std;vector<int> answer;bool check[101][101];int dx[] = {0,0,-1,1};int dy[] = {-1,1,0,0};void bfs(vector<string> maps, int k, int j) {queue<pair<int,int>> q;q.push({k,j});check[k][j] = true;int result = 0;while(!q.empty()) {int x = q.front().first;int y = q.front().second;result += (maps[x][y] - '0');q.pop();for(int i=0; i<4; i++) {int nx = dx[i] + x;int ny = dy[i] + y;if(nx < 0 || ny < 0 || nx >= maps.size() || ny >= maps[k].size() || check[nx][ny]) {continue;}if(maps[nx][ny] != 'X') {check[nx][ny] = true;q.push({nx,ny});}}}answer.push_back(result);}vector<int> solution(vector<string> maps) {for(int i=0; i<maps.size(); i++) {for(int j=0; j<maps[i].size(); j++) {if(maps[i][j] != 'X' && !check[i][j]) {bfs(maps,i,j);}}}sort(answer.begin(),answer.end());if(answer.size() == 0) { answer.push_back(-1); }return answer;}
cs 1. (0,0) 부터 시작하여 (0,1) (0,2) (0,3) ..... (1,0) (1,1) 과 같이 문자열 배열을 순회하며 'X' 가 아닐경우 bfs 탐색을 시작한다.
2. 탐색했던 섬을 다시 탐색하지 않기 위해서 bfs 탐색을 할때 bool check[101][101] 배열의 인덱스를 탐색시 true 로 바꿔준다.
3. 탐색이 끝나면 결과값을 answer 벡터에 저장
4. answer를 오름차순 정렬
728x90반응형'알고리즘 > 프로그래머스' 카테고리의 다른 글
[C++] 프로그래머스 광물 캐기 (0) 2023.03.23 [C++] 프로그래머스 리코쳇 로봇 (0) 2023.03.22 [C++] 백준 26091 현대모비스 소프트웨어 아카데미 (0) 2023.01.15 [C++] 프로그래머스 마법의 엘리베이터 (0) 2023.01.13 [C++] 프로그래머스 이모티콘 할인행사 (0) 2023.01.10