728x90

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

 

16197번: 두 동전

N×M 크기의 보드와 4개의 버튼으로 이루어진 게임이 있다. 보드는 1×1크기의 정사각형 칸으로 나누어져 있고, 각각의 칸은 비어있거나, 벽이다. 두 개의 빈 칸에는 동전이 하나씩 놓여져 있고,

www.acmicpc.net

#include<iostream>
#include<string>
#include<algorithm>
#include<vector>
using namespace std;
int row, col;
int dx[4]={0,0,1,-1};
int dy[4]={1,-1,0,0};

string map[20];
int num_of_out(int x1, int x2, int y1, int y2)//
{
    int cnt=0;
    if(x1>=row||x1<0)
        cnt++;
    if(x2>=row||x2<0)
        cnt++;
    if(y1>=col||y1<0)
        cnt++;
    if(y2>=col||y2<0)
        cnt++;
    return cnt;
}
bool is_blocking(int x, int y)
{
    if(x<0||x>=row||y<0||y>=col)
        return false;
    if(map[x][y]=='#')
        return true;
    return false;
}
int find_times(int times,int x1,int y1,int x2,int y2)
{
    if(times>10)
        return -1;
    if(num_of_out(x1,x2,y1,y2)==2)
        return -1;
    if(x1==x2&&y1==y2)
        return -1;
    if(num_of_out(x1,x2,y1,y2)==1)
        return times;
    int ans=-1;
    for (int i = 0; i < 4; i++){
        int nx1=x1+dx[i];
        int nx2=x2+dx[i];
        int ny1=y1+dy[i];
        int ny2=y2+dy[i];
        if(is_blocking(nx1,ny1)){
            nx1=x1;
            ny1=y1;
        }
        if(is_blocking(nx2,ny2)){
            nx2=x2;
            ny2=y2;
        }
        int a=find_times(times+1,nx1,ny1,nx2,ny2);
        if(ans==-1 || (a != -1) && ans > a)
            ans = a;
    }
    return ans;
}
int main(){
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);

    cin>>row>>col;
    int x1=-1,x2,y1,y2;
    for (int i = 0; i < row; i++)
        cin>>map[i];
    for (int i = 0; i < row; i++){
        for (int j = 0; j < col; j++){
            if(map[i][j]=='o'){
                if(x1==-1){
                    x1=i;
                    y1=j;
                }
                else{
                    x2=i;
                    y2=j;
                }
            }
        }
    }
    int res=find_times(0,x1,y1,x2,y2);
    cout<<res<<'\n';
    return 0;
}
bool is_blocking(int x, int y)
{
    if(x<0||x>=row||y<0||y>=col)
        return false;
    if(map[x][y]=='#')
        return true;
    return false;
}

여기 함수에서 마지막에 return false를 안 해주게 되면 return 값이 임의로 정해지기 때문에 조건에 해당하지 않는 경우에 대해서 꼭 리턴 값을 정해주어야 한다. 저것 때문에 틀려서 테스트 케이스는 다 돌아가는데 '틀렸습니다'가 나왔다.

728x90

'BOJ' 카테고리의 다른 글

<11048번> 이동하기  (0) 2022.01.13
<2580번> 스도쿠  (0) 2022.01.08
<14500번> 테트로미노  (1) 2022.01.06
<14888번> 연산자 끼워넣기  (0) 2022.01.05
<14225번> 부분수열의 합  (0) 2022.01.04

+ Recent posts