250x250
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 |
Tags
- 백준2251
- 순열
- Bfs와DFS
- 중복순열
- 코테
- 알고리즘개념
- 백준13458
- N과M
- 정올 1620
- 완탐
- 재귀함수
- 23288
- 삼성역테
- 자바
- 백준
- 코테준비
- 알고리즘
- java
- 백준15652
- 자바 코테
- 전화번호속의암호
- 완전탐색
- 볼륨 만들기
- BFS
- 주사위굴리기2
- 중복조합
- 에라토스테네스의채
- D드라이브생성
- 정보처리기사
- 파티션 크기 조정
Archives
- Today
- Total
뚱땅뚱땅
[문제] 백준 14503번 로봇 청소기 본문
728x90
풀이
방향전환만 헷갈리지 않으면 쉽게 풀 수 있다.
public class BOJ_14503 {
static int[] dx = { -1, 0, 1, 0 }; // 북동남서
static int[] dy = { 0, 1, 0, -1 };
static int[][] matrix; //
static int N,M;
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(in.readLine(), " ");
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
st = new StringTokenizer(in.readLine(), " ");
int x = Integer.parseInt(st.nextToken()); // 현재 위치
int y = Integer.parseInt(st.nextToken());
int d = Integer.parseInt(st.nextToken()); // 현재 방향
// init matrix
matrix = new int[N][M];
for (int i = 0; i < N; i++) {
st = new StringTokenizer(in.readLine(), " ");
for (int j = 0; j < M; j++) {
matrix[i][j] = Integer.parseInt(st.nextToken());
}
}
int sum = 1;
matrix[x][y] = 2; // 현재 위치 청소
boolean stop = false; // 더 이상 청소가 불가능하다면 stop = true
while (!stop) {
if (!canClean(x, y)) { // 청소할 곳이 없다면
int nx = x - dx[d]; // 방향 유지한 채로 후진한 칸
int ny = y - dy[d];
if (matrix[nx][ny] == 1) { // 한 칸 후진한 곳이 벽이라면
stop = true; // 멈춤
break;
} else { // 한칸 후진
x = nx;
y = ny;
}
}
// 4방향 중 청소할 곳이 있을 경우
else {
d = (d + 3) % 4; // 현재 방향의 왼쪽 방향
int nx = x + dx[d];
int ny = y + dy[d];
// 왼쪽 방향이 영역 내부에 있고 아직 청소 전이라면
if (nx >= 0 && nx < N && ny >= 0 && ny < M && matrix[nx][ny] == 0) {
x = nx; // 왼쪽으로 이동
y = ny;
sum++; // 청소한 영역 수 증가
matrix[x][y] = 2; // 청소 처리
}
}
}
System.out.println(sum); // 청소한 영역의 개수
}
// 현재 위치에서 동서남북 방향에 청소할 곳이 있는지 확인하는 함수
static boolean canClean(int a, int b) {
for (int dir = 0; dir < 4; dir++) {
int nx = a + dx[dir];
int ny = b + dy[dir];
if (matrix[nx][ny] == 0)
return true;
}
return false;
}
}
728x90
'알고리즘 > 백준' 카테고리의 다른 글
[문제] 백준 10972번 다음 순열 (0) | 2021.02.16 |
---|---|
[문제] 백준 9613번 GCD합 (0) | 2021.02.16 |
[문제] 백준 1967번 트리의 지름 (0) | 2021.02.15 |
[문제] 백준 2961번 도영이가 만든 맛있는 음식 (0) | 2021.02.15 |
[문제] 백준 14225번 부분수열의 합 (0) | 2021.02.15 |
Comments