Level 1. 바탕화면 정리
첫 매칭 위치를 반환하는 string.find()와 마지막 매칭 위치를 반환하는 string.rfind()를 이용해 해결했다.
#include <iostream>
#include <vector>
#include <climits>
#include <algorithm>
using namespace std;
vector<int> solution(vector<string> wallpaper)
{
int lux = INT_MAX, luy = INT_MAX;
int rdx = INT_MIN, rdy = INT_MIN;
int width = wallpaper.front().size(), height = wallpaper.size();
int x, pos;
for (x = 0; x < height; ++x)
if (wallpaper[x].find('#') != string::npos)
break;
lux = x;
for (x = 0; x < height; ++x)
if ((pos = wallpaper[x].find('#')) != string::npos)
luy = min(luy, pos);
for (x = height - 1; 0 <= x; --x)
if (wallpaper[x].rfind('#') != string::npos)
break;
rdx = x + 1;
for (x = height - 1; 0 <= x; --x)
if ((pos = wallpaper[x].rfind('#')) != string::npos)
rdy = max(rdy, pos + 1);
return vector<int>{lux, luy, rdx, rdy};
}
물론, 다른 사람의 풀이처럼 이중 for문 하나로 끝낼 수도 있지만 나는 모든 원소를 순회하고 싶지 않아서 각각을 나눠 계산했다.
#include <iostream>
#include <vector>
#include <climits>
#include <algorithm>
using namespace std;
vector<int> solution(vector<string> wallpaper)
{
int lux = INT_MAX, luy = INT_MAX;
int rdx = INT_MIN, rdy = INT_MIN;
int width = wallpaper.front().size(), height = wallpaper.size();
for (int x = 0; x < height; ++x)
{
for (int y = 0; y < width; ++y)
{
if (wallpaper[x][y] == '#')
{
lux = min(lux, x);
luy = min(luy, y);
rdx = max(rdx, x + 1);
rdy = max(rdy, y + 1);
}
}
}
return vector<int>{lux, luy, rdx, rdy};
}
'자료구조 & 알고리즘 > 프로그래머스' 카테고리의 다른 글
Level 1. 성격 유형 검사하기 (0) | 2023.03.10 |
---|---|
Level 1. 신고 결과 받기 (0) | 2023.03.09 |
Level 1. 둘만의 암호 (0) | 2023.03.07 |
Level 1. 부족한 금액 계산하기 (0) | 2023.03.06 |
Level 1. 신규 아이디 추천 (0) | 2023.03.05 |