반갑습니다!

[SWEA] 1215 회문1 본문

알고리즘 문제 풀이

[SWEA] 1215 회문1

김덜덜이 2020. 4. 18. 22:27
SW Expert Academy
SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!
swexpertacademy.com

풀이

Stack을 이용하여 회문을 찾아주었다. 회문의 길이가 짝수인 경우와 홀수인 경우를 구분하였고, 가로방향 회문을 먼저 찾고 세로방향 회문을 찾아주었다.

코드

#include <iostream>
#include <stack>
using namespace std;

void clear(stack<char>& s) {
    while (!s.empty()) s.pop();
}

int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);

    char board[8][9];

    for (int t = 1; t <= 1; t++) {
        int ans = 0;
        int size;
        cin >> size;
        for (int i = 0; i < 8; i++)
            for (int j = 0; j < 8; j++)
                cin >> board[i][j];
        stack<char> s;
        for (int i = 0; i < 8; i++) {
            for (int j = 0; j <= 8 - size; j++) {
                clear(s);
                for (int l = 0; l < size; l++) {
                    if (size % 2 == 1) {
                        if (l < (size - 1) / 2) s.push(board[i][j + l]);
                        else if (l > (size - 1) / 2) {
                            if (board[i][j + l] != s.top()) break;
                            s.pop();
                        }
                    }
                    else {
                        if (l < size / 2) s.push(board[i][j + l]);
                        else {
                            if (board[i][j + l] != s.top()) break;
                            s.pop();
                        }
                    }
                }
                if (s.empty()) ans++;
            }
        }

        for (int j = 0; j < 8; j++) {
            for (int i = 0; i <= 8 - size; i++) {
                clear(s);
                for (int l = 0; l < size; l++) {
                    if (size % 2 == 1) {
                        if (l < (size - 1) / 2) s.push(board[i + l][j]);
                        else if (l > (size - 1) / 2) {
                            if (board[i + l][j] != s.top()) break;
                            s.pop();
                        }
                    }
                    else {
                        if (l < size / 2) s.push(board[i + l][j]);
                        else {
                            if (board[i + l][j] != s.top()) break;
                            s.pop();
                        }
                    }
                }
                if (s.empty()) ans++;                    
            }
        }
        cout << "#" << t << ' ' << ans << '\n';
    }
    return 0;
}

'알고리즘 문제 풀이' 카테고리의 다른 글

[SWEA] 1213 String  (0) 2020.04.18
[SWEA] 1225 암호생성기  (0) 2020.04.18
[SWEA] 2805 농작물 수확하기  (0) 2020.04.18
[백준] 17822 원판 돌리기  (0) 2020.04.18
[프로그래머스] 방문 길이  (0) 2020.04.17