winter intern #2
1. 문제 설명
- (5,5) 2차원 평면에서 (0,0)에 물체가 있다. 이 물체에 명령어 "U","D","R","L"을 주어서 각각 위, 아래, 오른쪽, 왼쪽으로 움직일 수 있다.
- 이때, 이 물체가 움직인 거리의 총 합을 구하라.
- 단, 물체는 한번 지난 경로를 중복하여 지날때는 이를 무시한다.
- 평면 밖을 나가게 된다면, 이를 무시하고 움직이지 않는다.
2. 나의 코드
import java.util.*;
class Solution {
public int solution(String dirs) {
int answer = 7;
int lx =0,ly=0;
String [] directs = dirs.split("");
boolean flag = true;
ArrayList <Vec> vlist = new ArrayList<Vec>();
for(int i=0;i<directs.length;i++){
int fx = lx;
int fy = ly;
flag = true;
Vec vc = new Vec();
vc.Fset(fx,fy);
if(directs[i].equals("U")){
if(ly+1 > 5){
continue;
}
else
ly++;
}
else if(directs[i].equals("D")){
if(ly-1 < -5){
continue;
}
else
ly--;
}
else if(directs[i].equals("R")){
if(lx-1 > 5){
continue;
}
else
lx++;
}
else if(directs[i].equals("L")){
if(lx-1 < -5){
continue;
}
else
lx--;
}
vc.Lset(lx,ly);
if(lx >= -5 && lx <= 5 && ly >= -5 && ly <= 5){
if(i==0)
vlist.add(vc);
else{
int size = vlist.size();
for(int j =0;j<size;j++){
Vec vtemp = vlist.get(j);
String ftemp = "";
String ltemp = "";
ftemp += String.valueOf(fx);
ftemp += String.valueOf(fy);
ltemp += String.valueOf(lx);
ltemp += String.valueOf(ly);
if(vtemp.Fget().equals(ftemp) && vtemp.Lget().equals(ltemp)){
flag = false;
break;
}
}
if(flag)
vlist.add(vc);
}
}
}
answer = vlist.size();
return answer;
}
}
class Vec {
String fv = "";
String lv = "";
public void Fset(int x, int y){
fv += String.valueOf(x);
fv += String.valueOf(y);
}
public void Lset(int x, int y){
lv += String.valueOf(x);
lv += String.valueOf(y);
}
public String Fget(){
return fv;
}
public String Lget(){
return lv;
}
}
'Computer Science > 알고리즘 문제풀이' 카테고리의 다른 글
| Programmers > 연습문제 > #31 2 x n 타일링 (0) | 2018.11.14 |
|---|---|
| Programmers > 스택/큐(Stack/Queue) > #30 기능개발 (0) | 2018.11.12 |
| Programmers > 깊이/너비 우선 탐색(DFS/BFS) > #27 타겟 넘버 [JAVA] (0) | 2018.11.07 |
| Programmers > 완전탐색 > #26 소수찾기(level 2) [JAVA] (0) | 2018.11.07 |
| Programmers > #25 winter recruit > #1 [JAVA] (0) | 2018.10.29 |