[백준] 16441번 아기돼지와 늑대 (C++)

2025. 11. 30. 20:22·Algorithm
728x90

https://www.acmicpc.net/problem/16441

 

 

이 문제는 N X M 격자그래프 배열이 주어지며 이때 초원, 빙판, 산, 늑대가 주어지며 이때 늑대가 움직일 수 있는 경로를 탐색해서

늑대가 못가는 경로에는 P를 출력하는 문제이다.

 

이때 빙판을 밟으면 이전에 빙판을 밟았던 방향으로 계속 이동하며 산이나 초원을 만날때까지 계속 움직여야 한다.

 

이후 부딪히고 난 이후 다른방향으로 이동할 수 있다.

 

따라서 모든 경로를 탐색하기 위해 bfs(너비 우선 탐색)을 사용하여 모든 갈 수 있는 경로를 방문체크하여 탐색하였다.

 

이때 빙판을 마주칠 경우 while 문을 사용하여 빙판을 마주치치않을때까지 반복하였다.

 

 

정답코드

#include <bits/stdc++.h>
using namespace std;
typedef pair<int, int> pii;
typedef long long ll;
#define endl "\n"
#define MAX 1e9

struct coordinate {
    int x;
    int y;
    int r;
};

struct horse {
    int x;
    int y;
    int dir;
};

// int dx[] = {-1, 1, 0, 0, 1, -1, -1, 1};
// int dy[] = {0, 0, -1, 1, -1, 1, -1, 1};
int dx[] = {0, 0, 1, -1};
int dy[] = {1, -1, 0, 0};
int N, M;
char graph[101][101];
queue<pii> q;
bool visited[101][101];

void bfs() {
    while(!q.empty()) {
        int x = q.front().first;
        int y = q.front().second;
        q.pop();

        for(int i = 0; i < 4; i++) {
            int nx = x + dx[i];
            int ny = y + dy[i];

            if(nx < 0 || nx >= N || ny < 0 || ny >= M) continue;

            if(graph[nx][ny] == '.' && !visited[nx][ny]) {
                q.push({nx, ny});
                visited[nx][ny] = true;
            }
            else {
                while(graph[nx][ny] != '.') {
                    if(graph[nx][ny] == '#') {      // 벽인 경우
                        nx -= dx[i];
                        ny -= dy[i];
                        break;
                    }
                    nx += dx[i];
                    ny += dy[i];
                }
                if(!visited[nx][ny]) {
                    q.push({nx, ny});
                    visited[nx][ny] = true;
                }
            }
        }
    }
}

void Print() {
    for(int i = 0; i < N; i++) {
        for(int j = 0; j < M; j++) {
            cout << visited[i][j] << " ";
        }
        cout << endl;
    }
}

void solve() {
    bfs();

    for(int i = 0; i < N; i++) {
        for(int j = 0; j < M; j++) {
            if(graph[i][j] != '.') {
                cout << graph[i][j];
            }
            else {
                if(!visited[i][j]) {
                    cout << "P";
                }
                else cout << graph[i][j];
            }
        }
        cout << endl;
    }
}

void input() {
    cin >> N >> M;

    for(int i = 0; i < N; i++) {
        for(int j = 0; j < M; j++) {
            cin >> graph[i][j];

            if(graph[i][j] == 'W') {
                q.push({i, j});
                visited[i][j] = true;
            }
        }
    }
}


int main() {
    ios::sync_with_stdio(0);
    cin.tie(0), cout.tie(0);

    input();
    solve();
}

 

 

728x90
저작자표시 (새창열림)

'Algorithm' 카테고리의 다른 글

[백준] 2613번 숫자구슬 (C++)  (0) 2025.12.02
[백준] 1781번 컵라면 (C++)  (0) 2025.12.01
[백준] 7453번 합이 0인 네 정수 (C++)  (0) 2025.11.29
[백준] 17485번 진우의 달 여행 (Large) (C++)  (1) 2025.11.28
[백준] 13904번 과제 (C++)  (0) 2025.11.27
'Algorithm' 카테고리의 다른 글
  • [백준] 2613번 숫자구슬 (C++)
  • [백준] 1781번 컵라면 (C++)
  • [백준] 7453번 합이 0인 네 정수 (C++)
  • [백준] 17485번 진우의 달 여행 (Large) (C++)
쿨쿨.
쿨쿨.
  • 쿨쿨.
    All of the life
    쿨쿨.
  • 전체
    오늘
    어제
    • 분류 전체보기 (279)
      • Programming (47)
        • C, C++ (18)
        • Python (6)
        • Java (1)
        • HTML,CSS,JS (3)
        • SQL(DB) (13)
        • SpringBoot (3)
        • Android (2)
        • CI,CD (1)
      • Algorithm (173)
        • Review (4)
      • Security (14)
        • WebHacking (3)
        • Websecurity (11)
      • OS (19)
        • Linux (12)
        • Mac os (2)
      • 머신러닝 (1)
      • CS(Computer Science) (12)
        • 컴퓨터 네트워크 (3)
        • 컴퓨터 구조 (1)
        • 인공지능 (8)
      • Docker (1)
      • Dev Book Review (3)
        • Clean Code (1)
        • Effective Java (0)
        • Real MySQL (2)
      • SWM (1)
      • Review (6)
      • AWS (2)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    WebSecurity
    트리
    우선순위큐
    구현
    브루트포스
    wargame
    누적합
    c언어
    투포인터
    비트마스킹
    Leviathan
    우선순위 큐
    정렬
    이분탐색
    Bandit
    다이나믹 프로그래밍
    백트래킹
    DP
    그래프 이론
    재귀
    깊이우선탐색
    시뮬레이션
    에라토스테네스의 체
    백준
    BFS
    그리디
    linux
    코딩
    DFS
    다익스트라
  • 최근 댓글

  • 최근 글

  • 250x250
  • hELLO· Designed By정상우.v4.10.6
쿨쿨.
[백준] 16441번 아기돼지와 늑대 (C++)
상단으로

티스토리툴바