(C++) 백준 18428 감시 피하기

mnaz·2021년 10월 10일

dfs 할때 범위 주의 ~~

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

char arr[7][7];
int N;
bool ans = false;
vector<pair<int, int> > Tpos;

void solve(int y, int x, int cnt){


    if(y>=N && x>=N) return ;
    if(ans) return ;

    if(cnt==3){

        bool answer = true;

        for(int k=0; k<(int)Tpos.size() && answer; k++){
            int xx = Tpos[k].second;
            int yy = Tpos[k].first;

            for(int i=xx+1; i<N && answer; i++){
                if(arr[yy][i]=='O') break;
                else if(arr[yy][i]=='S') {
                    answer=false;

                }
            }

            for(int i=xx-1; i>=0 && answer; i--){
                if(arr[yy][i]=='O') break;
                else if(arr[yy][i]=='S') {
                    answer=false;
                }
            }

            for(int j=yy+1; j<N && answer; j++){
                if(arr[j][xx]=='O') break;
                else if(arr[j][xx]=='S') {
                    answer=false;
                }
            }

            for(int j=yy-1; j>=0 && answer; j--){
                if(arr[j][xx]=='O') break;
                else if(arr[j][xx]=='S') {
                    answer=false;
                }
            }

        }

        if(answer) ans=true;
        return ;
    }


    int j=0;
    for(int i=y; i<N; i++){
        if(i==y) j=x;
        else j=0;
        for(; j<N; j++){
            if(arr[i][j]=='X'){
                arr[i][j]='O';
                solve(i, j, cnt+1);
                arr[i][j]='X';
            }
        }
    }

}



int main(){

    cin>>N;

    char c;
    for(int i=0; i<N; i++){
        for(int j=0; j<N; j++){
            cin>>c;
            arr[i][j]=c;
            if(c=='T') Tpos.push_back({i,j});
        }
    }


    solve(0, 0, 0);


    if(ans) cout<<"YES";
    else cout<<"NO";

}

0개의 댓글