废话不多说,直接看代码:
/*
* Copyright (c) Huawei Technologies Co., Ltd. 2019-2021. All rights reserved.
* Description: 上机编程认证
* Note: 缺省代码仅供参考,可自行决定使用、修改或删除
*/
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <set>
#include <unordered_set>
using namespace std;
class Solution {
public:
// 待实现函数,在此函数中填入答题代码;
int GetMatchedWordCount(const vector<vector<char>> &charMatrix, const vector<string> &words)
{
this->words = words;
m = charMatrix.size(), n = charMatrix[0].size();
mat = new char *[m];
for (int i = 0; i < m; i++) {
mat[i] = new char[n];
for (int j = 0; j < n; j++) {
mat[i][j] = charMatrix[i][j];
}
}
visi = new bool *[m];
for (int i = 0; i < m; i++) {
visi[i] = new bool[n];
}
getMaxLen();
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
resetVisi();
dfs(i, j, "");
if (found.size() == words.size()) {
return found.size();
}
}
}
return found.size();
}
void dfs(int i, int j, string word)
{
if (i < 0 || j < 0 || i >= m || j >= n || visi[i][j]) {
return;
}
if (found.size() >= words.size()) {
return;
}
if (word.size() > maxLen + 2) {
return;
}
findWord(word);
string cur = word + mat[i][j];
visi[i][j] = true;
dfs(i + 1, j, cur);
dfs(i - 1, j, cur);
dfs(i, j + 1, cur);
dfs(i, j - 1, cur);
visi[i][j] = false;
}
void resetVisi()
{
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
visi[i][j] = false;
}
}
}
bool findWord(const string &word)
{
for (const auto &item : words) {
if (item.size() != word.size()) {
continue;
}
int sz = item.size();
int i = 0;
for (i = 0; i < sz; i++) {
if (word[i] != '?' && word[i] != item[i]) {
break;
}
}
if (i == sz) {
found.insert(item);
}
if (word.find('?') == string::npos) {
return true;
}
}
return false;
}
void getMaxLen()
{
maxLen = 0;
for (const string &word : words) {
if (word.size() > maxLen) {
maxLen = word.size();
}
}
}
private:
int m;
int n;
int maxLen = 0;
char **mat;
bool **visi;
vector<string> words;
int ans = 0;
unordered_set<string> found;
};
inline int ReadInt()
{
int number;
cin >> number;
return number;
}
template <typename T>
inline vector<T> ReadVector(int size)
{
vector<T> objects(size);
for (int i = 0; i < size; ++i) {
cin >> objects[i];
}
return objects;
}
int main()
{
int row = ReadInt();
int col = ReadInt();
vector<vector<char>> charMatrix;
for (int i = 0; i < row; i++) {
vector<char> oneRow = ReadVector<char>(col);
charMatrix.push_back(oneRow);
}
int wordsNum = ReadInt();
vector<string> words = ReadVector<string>(wordsNum);
Solution solution;
int result = solution.GetMatchedWordCount(charMatrix, words);
cout << result << endl;
return 0;
}