본문 바로가기

algorithm

1450 로봇청소기

#include <iostream>
using namespace std;
int N,M,r,c,d,ans,z;
int map[51][51];
int dx [4] = {-1,0,1,0}; //N,W,S,E
int dy [4] = {0,1,0,-1};
bool clean[51][51];
bool running = true;
int getLeftDir(int d){
	if(d == 1) return 0;
	if(d == 0) return 3;
	if(d == 3) return 2;
	if(d == 2) return 1;
}
int getBackDir(int d){
	if(d == 1) return 3;
	if(d == 2) return 0;
	if(d == 3) return 1;
	if(d == 0) return 2;
}
int main(){
	cin>>N>>M>>r>>c>>d;
	for(int i = 0; i< N; i++)for(int j = 0; j < M;j++) cin>>map[i][j];
	
	while(running){
		clean[r][c] = true;
		ans++;
		z = 0;
		while(true){
		d = getLeftDir(d);
		int x = r + dx[d], y = c + dy[d];
		if(x < 0 || x >= N || y < 0 || y >= M || map[x][y] || clean[x][y]){
			int t = getBackDir(d);	
			z++;
			if(z != 4) continue;
			if(map[r + dx[t]][c + dy[t]] == 1) {
				running = false;
				break;
			}
			else {
				r += dx[t]; // go backward
				c += dy[t];
				z = 0;
			}
		}
		else {
			r = x; c = y;
			break;
		}
		}
		}
	cout << ans;
	return 0;
}

'algorithm' 카테고리의 다른 글

2533  (0) 2022.05.19
2110,2447  (0) 2022.05.18
16888 루트 게임  (0) 2022.05.15
15877  (0) 2022.05.14
1068  (0) 2022.05.13