小言_互联网的博客

Programming Challenges 习题 3.8.2

320人阅读  评论(0)

PC/UVa:110302/10010

Where’s Waldorf?

书上有一个提示,说是否一定要写8个方向的循环,还是可以写一个函数来判断8个方向。既然提示了,那就按照书上的提示来写了。

#include <iostream>
#include <vector>
#include <string>

using namespace std;

bool find(const vector<vector<char>> &vvcRec, const string &strWord, int x, int y, int dirx, int diry)
{
	size_t k, i, j;
	for (k = 0, i = x, j = y;
		k < strWord.size() && i >= 0 && i < vvcRec.size() && j >= 0 && j < vvcRec[0].size();
		k++, i += dirx, j += diry)
	{
		if (vvcRec[i][j] != strWord[k]) break;
	}
	if (k != strWord.size()) return false;
	else{
		cout << x + 1 << ' ' << y + 1 << endl;
		return true;
	}
}

int main()
{
	int T = 0;
	cin >> T;
	cin.get();
	cin.get();
	for (int t = 0; t < T; t++)
	{
		int m = 0, n = 0, k = 0;
		cin >> m >> n;
		vector<vector<char>> vvcRec(m, vector<char>(n, '\0'));
		for (int i = 0; i < m; i++)
		{
			for (int j = 0; j < n; j++)
			{
				cin >> vvcRec[i][j];
				vvcRec[i][j] = tolower(vvcRec[i][j]);
			}
		}
		cin >> k;
		cin.get();
		vector<string> vstrWord;
		string strWord;
		while (getline(cin, strWord)){
			if (strWord.empty()) break;
			for (char& ch : strWord)
			{
				ch = tolower(ch);
			}
			vstrWord.push_back(strWord);
		}
		for (auto word : vstrWord)
		{
			bool bFind = false;
			for (int i = 0; i < m; i++)
			{
				for (int j = 0; j < n; j++)
				{
					if (vvcRec[i][j] == word[0] &&
						(
						find(vvcRec, word, i, j, -1, 0) ||
						find(vvcRec, word, i, j, -1, 1) ||
						find(vvcRec, word, i, j, 0, 1) ||
						find(vvcRec, word, i, j, 1, 1) ||
						find(vvcRec, word, i, j, 1, 0) ||
						find(vvcRec, word, i, j, 1, -1) ||
						find(vvcRec, word, i, j, 0, -1) ||
						find(vvcRec, word, i, j, -1, -1)
						)
						){
						bFind = true;
						break;
					}
				}
				if (bFind) break;
			}
		}
		if (t != T - 1) cout << endl;
	}
	return 0;
}
/*
1

8 11
abcDEFGhigg
hEbkWalDork
FtyAwaldORm
FtsimrLqsrc
byoArBeDeyv
Klcbqwikomk
strEBGadhrb
yUiqlxcnBjf
4
Waldorf
Bambi
Betty
Dagbert
*/


转载:https://blog.csdn.net/RayoNicks/article/details/101218685
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场