1일1알

백준 13565번 침투 C++ 본문

알고리즘

백준 13565번 침투 C++

영춘권의달인 2023. 1. 25. 12:06

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

 

13565번: 침투

첫째 줄에는 격자의 크기를 나타내는  M (2 ≤ M ≤ 1,000) 과 N (2 ≤ N ≤ 1,000) 이 주어진다. M줄에 걸쳐서, N개의 0 또는 1 이 공백 없이 주어진다. 0은 전류가 잘 통하는 흰색, 1은 전류가 통하지 않

www.acmicpc.net

 

bfs/dfs

 

#include <iostream>
#include <string>
#include <vector>
#include <math.h>
#include <algorithm>
#include <utility>
#include <stack>
#include <queue>
#include <math.h>
#include <set>
#include <map>
#include <list>
#include <unordered_map>
#include <unordered_set>
#include <iomanip>
#include <limits.h>

using namespace std;
using int64 = long long; 

int dRow[4] = { -1,0,1,0 };
int dCol[4] = { 0,1,0,-1 };

int m, n;
vector<vector<char>> board;
vector<vector<bool>> found;

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);

    cin >> m >> n;
    board = vector<vector<char>>(m, vector<char>(n));
    found = vector<vector<bool>>(m, vector<bool>(n, false));
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            cin >> board[i][j];
        }
    }
    queue<pair<int, int>> q;
    for (int i = 0; i < n; i++) {
        if (board[0][i] == '1') continue;
        q.push({ 0,i });
        found[0][i] = true;
    }
    bool ans = false;
    while (!q.empty()) {
        auto curr = q.front();
        q.pop();
        if (curr.first == m - 1) {
            ans = true;
            break;
        }
        for (int i = 0; i < 4; i++) {
            int nextRow = curr.first + dRow[i];
            int nextCol = curr.second + dCol[i];
            if (nextRow < 0 || nextRow >= m) continue;
            if (nextCol < 0 || nextCol >= n) continue;
            if (board[nextRow][nextCol] == '1') continue;
            if (found[nextRow][nextCol]) continue;
            q.push({ nextRow,nextCol });
            found[nextRow][nextCol] = true;
        }
    }
    if (ans) cout << "YES";
    else cout << "NO";
}