๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm ๐Ÿง‘๐Ÿป‍๐Ÿ’ป/ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค(Programmers)

[c++] ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ๋ฐฉ๋ฌธ ๊ธธ์ด( Level 2)

by ์•ˆ์ฃผํ˜• 2021. 11. 8.

๋ฌธ์ œ

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ๋ฐฉ๋ฌธ ๊ธธ์ด

 

programmers.co.kr

 

์ฝ”๋“œ

#include <string>
#include <vector>
#include <map>

using namespace std;

bool range_check(int x, int y){
    if(x>5||y>5||x<-5||y<-5) return false;
    return true;
}

int solution(string dirs) {

    map<vector<int>,int>check;

    int answer = 0;
    int x=0,y=0;

 for(int i=0; i<dirs.length(); i++){
        char dir = dirs[i];
        if(dir=='R'){
            if(range_check(x+1,y)){

                vector<int> temp1{x,y,x+1,y};
                vector<int> temp2{x+1,y,x,y};
                if(check[temp1]==0&&check[temp2]==0) answer++;
                check[temp1]++;
                check[temp2]++;
                x+=1;
            }
        }
        if(dir=='L'){
            if(range_check(x-1,y)){
                vector<int> temp1{x,y,x-1,y};
                vector<int> temp2{x-1,y,x,y};
                if(check[temp1]==0&&check[temp2]==0) answer++;
                check[temp1]++;
                check[temp2]++;                
                x-=1;

            }
        }
        if(dir=='D'){
            if(range_check(x,y-1)){
                vector<int> temp1{x,y,x,y-1};
                vector<int> temp2{x,y-1,x,y};
                if(check[temp1]==0&&check[temp2]==0) answer++;
                check[temp1]++;
                check[temp2]++;
                y-=1;                
            }
        }
        if(dir=='U'){
            if(range_check(x,y+1)){

                vector<int> temp1{x,y,x,y+1};
                vector<int> temp2{x,y+1,x,y};
                if(check[temp1]==0&&check[temp2]==0) answer++;
                check[temp1]++;
                check[temp2]++;
                y+=1;
            }
        }
 }
    return answer;
}

 

ํ’€์ด

์ด ๋ฌธ์ œ์˜ ํ•ต์‹ฌ์€ ๋ฐฉํ–ฅ์„ฑ์ด ์—†๋‹ค๋Š” ๊ฒƒ์ž…๋‹ˆ๋‹ค. ์ฆ‰ (-1,0)์—์„œ (0,0)์œผ๋กœ ํ™”์‚ดํ‘œ์™€ (0,0)์—์„œ (-1,0)์œผ๋กœ์˜ ํ™”์‚ดํ‘œ๊ฐ€ ๊ฐ™๋‹ค๋Š” ์˜๋ฏธ์ธ๋ฐ ๋งŒ์•ฝ ์œ„ ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์ฃผ์ง€ ์•Š๋Š”๋‹ค๋ฉด ํ…Œ์ŠคํŠธ์ผ€์ด์Šค 8๋ฒˆ๋ถ€ํ„ฐ ์ญ‰ ์˜ค๋‹ต์ฒ˜๋ฆฌ๊ฐ€ ๋‚ฉ๋‹ˆ๋‹ค.

์ €๋Š” map ํ…Œ์ด๋ธ”์„ ํ™œ์šฉํ•˜์—ฌ  temp1, temp2์™€ ๊ฐ™์ด ์–‘๋ฐฉํ–ฅ ํ™”์‚ดํ‘œ์˜ ๋ฐฉ๋ฌธ์ฒ˜๋ฆฌ ์—ฌ๋ถ€๋ฅผ ํŒ๋‹จํ•˜์—ฌ ์นด์šดํ„ฐ๋ฅผ ์„ธ์–ด์„œ ํ•ด๊ฒฐํ–ˆ์Šต๋‹ˆ๋‹ค.

๋Œ“๊ธ€