首页 > 其他分享 >贪吃蛇(华为机试)

贪吃蛇(华为机试)

时间:2022-11-11 19:33:41浏览次数:55  
标签:ch int second 华为 贪吃蛇 机试 include dir first

#include<deque>
#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
//每次蛇移动只会有3种情况:
// //1.撞墙(坐标越界)直接返回长度;
//2.空格 第一步:将空格坐标body.push_front({x,y}),将该坐标设置为'H',第二步:将尾巴坐标设置为'E',然后弹出尾巴坐标body.pop_back()。
//3.食物 直接body.push_front({x,y}),设置坐标为'H';
/*D G L G G
3 3
F F F
F F H
E F E*/
/*U G G
3 3
F F F
F F H
E F E*/
/*DGL GUG RG
3 3
F F F
F F H
E F E*/ 
using namespace std;
int main() {
	string op;
	getline(cin,op);
	int n = 0;
	int m = 0;
	string t;
	cin >> n >> m; getline(cin, t);
	string c;
	int x=0;
	int y = 0;
	vector<string> matrix(n,string());
	for (int i = 0; i < n; ++i) {
		getline(cin, c);
		for (char j:c) {
			if (j != ' ') {
				matrix[i].push_back(j);
			}
		}
	}
	for (int i = 0; i < matrix.size();++i) {
		for (int j = 0;j<matrix[i].size(); ++j) {
			if (matrix[i][j] == 'H') {
				x = i;
				y = j;
			}
		}
	}
	pair<int, int> dir{-1,0};
	int len = 1;
	deque<pair<int, int>> body{{x,y}};
	for (auto ch : op) {
		if (ch == 'L') {
			 dir.first=0;
			 dir.second = -1;
		}
		else if (ch == 'R') {
			dir.first = 0;
			dir.second = 1;
		}
		else if (ch == 'U') {
			dir.first = -1;
			dir.second = 0;
		}
		else if (ch == 'D') {
			dir.first = 1;
			dir.second = 0;
		}
		else if (ch == 'G') {
			x=x+dir.first;
			y=y+dir.second;
			cout<<x<<' ' << y << endl;
			if (x < 0 || x >= n || y < 0 || y >= m) {
				cout << len;
				return 0;
			}
			if (matrix[x][y] == 'F') {
				++len;
				matrix[x][y] = 'H';
				body.push_back({ x,y });
			}
			else if (matrix[x][y] == 'H') {
				cout << len;
				return 0;
			}
			else if (matrix[x][y] == 'E') {
				auto tempx = body.back().first;
				auto tempy = body.back().second;
				body.push_front({x,y});
				body.pop_back();
				matrix[tempx][tempy] = 'E';
				matrix[x][y] = 'H';
			}
		}

	}
	cout << len;
	return 0;
}

标签:ch,int,second,华为,贪吃蛇,机试,include,dir,first
From: https://www.cnblogs.com/chunbai11/p/16881532.html

相关文章