ZOJ-1258

来源:互联网 发布:php是什么软件 编辑:程序博客网 时间:2024/05/21 18:31

比较无聊的搜索。。两个矩阵各DFS搜一记,找出相同的四字含两个元音字母的串,注意字串连接的条件是边和角,因此搜索方向是八个方向,虽然简单还是要100多行代码。。蛋疼

#include<cstdio>#include<vector>#include<set>#include<cstring>#include<iostream>using namespace std;namespace{char s[4][4], t[4][4];int dir[8][2] = { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 }, { -1, -1 }, {-1, 1 }, { 1, -1 }, { 1, 1 } };bool flag[4][4], vowel[26];vector<char> V;set<string> S;void init_vowel(){memset(vowel, 0, sizeof(26));vowel['A' - 'A'] = true;vowel['O' - 'A'] = true;vowel['E' - 'A'] = true;vowel['I' - 'A'] = true;vowel['U' - 'A'] = true;vowel['Y' - 'A'] = true;}bool valid(int r, int c){return r >= 0 && r < 4 && c >= 0 && c < 4;}bool word(const vector<char> &v){int count = 0;for (size_t i = 0; i < v.size(); i++)if (vowel[v[i] - 'A'])count++;return count == 2;}string str(const vector<char> &v){string s;for (size_t i = 0; i < v.size(); i++)s += v[i];return s;}void dfs(int depth, int r, int c){if (depth == 4){if (word(V))S.insert(str(V));return;}int row, col;for (int k = 0; k < 8; k++){row = r + dir[k][0];col = c + dir[k][1];if (valid(row, col) && !flag[row][col]){flag[row][col] = true;V.push_back(s[row][col]);dfs(depth + 1, row, col);V.pop_back();flag[row][col] = false;}}}void dfs_each(){memset(flag, 0, sizeof(flag));V.clear();S.clear();for (int i = 0; i < 4; i++)for (int j = 0; j < 4; j++){flag[i][j] = true;V.push_back(s[i][j]);dfs(1, i, j);V.pop_back();flag[i][j] = false;}}}int main(){init_vowel();char temp[2];int cs = 0;while (scanf("%s", temp), strcmp(temp, "#")){if (cs++)putchar('\n');s[0][0] = temp[0];for (int i = 1; i < 8; i++){scanf("%s", temp);if (i < 4)s[0][i] = temp[0];elset[0][i - 4] = temp[0];}for (int i = 1; i < 4; i++)for (int j = 0; j < 8; j++){scanf("%s", temp);if (j < 4)s[i][j] = temp[0];elset[i][j - 4] = temp[0];}dfs_each();set<string> src = S;memcpy(s, t, sizeof(t));dfs_each();bool common = false;for (set<string>::iterator it = S.begin(); it != S.end(); it++)if (src.find(*it) != src.end()){common = true;cout << *it << endl;}if (!common)puts("There are no common words for this pair of boggle boards.");}return 0;}


0 0
原创粉丝点击