백준 14503

HR·2022년 5월 26일
0

알고리즘 문제풀이

목록 보기
29/50

백준 14503 : 로봇 청소기

구현할 기능들
1. 입력받기
2. 왼쪽을 확인하는 함수 searchLeft
3. 4번 회전한 뒤 뒤쪽을 확인해야 함
4. 뒤쪽이 벽이라면 그때까지 쌓인 값들 출력

정답 코드

#include <iostream>
#include <algorithm>

using namespace std;

int n, m;
int r, c, d;
int map[51][51];
int ans, cnt;

int dy[4] = {0, 1, 0, -1};
int dx[4] = {-1, 0, 1, 0};
int cleaned[51][51];

void input() {
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);
	
	cin>>n>>m;
	cin>>r>>c>>d;
	for(int i=0; i<n; i++) {
		for(int j=0; j<m; j++) {
			cin>>map[i][j];
		}
	}
}


void searchLeft(int x, int y, int d) {
	
	//repeat 4 times
	for(int i=0; i<4; i++) {
		//left : map(ny, nx)
		int nd = (d+3-i)%4;
		int ny = y + dy[nd];
		int nx = x + dx[nd];
		
		
		if(ny<0 || nx<0 || ny>=m || nx>=n) continue; //if go out of the map
		if(map[nx][ny]==1) continue; //if encounters wall
		
		//check whether map is 0
		if(cleaned[nx][ny]==0 && map[nx][ny]==0) {			
			cleaned[nx][ny]=1;
//			cout<<"("<<nx<<","<<ny<<"), nd: "<<nd<<'\n';
			cnt++;
			searchLeft(nx, ny, nd);
		}
		
	}
	
	
	//after 4 times : check behind
	//behind
	int back_d = (d+2)%4;
	int back_y = y + dy[back_d];
	int back_x = x + dx[back_d];
	
	if(back_y<0 || back_x<0 || back_y>=m || back_x>=n) { //if go out of the map
		return;
	}
	
	if(map[back_x][back_y] == 1) { //if encounters wall
			cout<<cnt<<'\n';
			exit(0);
	}
	else { //go behind
		searchLeft(back_x, back_y, d);
	}

}


int main() {	

	input();
	
	cleaned[r][c]=1; cnt++;
	searchLeft(r, c, d);
	
	return 0;
}

0개의 댓글