UVa232
采用数据结构与大概流程
这题与UVa227比较相似
1.因为要输出横向的单词与纵向单词,所以采用两个map来分别记录搜索到的单词和单词首字母所在的位置
2.同样不知道要解答多少个字谜,所以还是while(true)的结构
3.同样要注意输入输出格式问题,比如当输入“1 1 *”时没有单词,但要注意Across和Down也是要输出的,还有序号十位数与个位数前的空格不同
算法概述
1.输入一个字谜
2.读取横向单词:用for循环控制行数,用while(true)来控制一行中查找单词,并同时记录下每个单词首字母的序号
3.首字母的序号判断:
- 当这个字母上方和右方处于边界的时候这个字母一定是单词的首字母
- 当这个字母左边或者上方是*时,一定是首字母
- 在puzzleNum这个二维数组中给对应位置赋值
4.当字母右方为字谜边界或*时把这个单词与对应序号压入map中
5.读取纵向单词同理
6.输出
代码实现
#include <iostream>
#include <string>
#include <map>
using namespace std;
int sum = 0;
map<int, string> across;
map<int, string> down;
void print(int i)
{
if (i > 1)
cout << endl;
cout << "puzzle #" << i << ":" << endl;
//打印横向
cout << "Across" << endl;
auto across_it = across.cbegin();
while (across_it != across.cend())
{
if (across_it->first < 10)
cout << " ";
else
cout << " ";
cout << across_it->first << "." << across_it->second<<endl;
across_it++;
}
//打印纵向
cout << "Down" << endl;
auto down_it = down.cbegin();
while (down_it != down.cend())
{
if (down_it->first < 10)
cout << " ";
else
cout << " ";
cout<< down_it->first << "." << down_it->second<<endl;
down_it++;
}
}
int main()
{
int r, c;
int x, y;
string word;
int num = 1;
char puzzle[10][10];
int puzzleNum[10][10];
while (true)
{
//输入
cin >> r;
if (r == 0)
break;
cin >> c;
sum++;
num = 1;
across.clear();
down.clear();
for (int i = 0; i < r; i++)
{
for (int j = 0; j < c; j++)
{
cin >> puzzle[i][j];
}
}
//读取横向单词
for (int i = 0; i < r; i++)
{
word.clear();
int pointW = 0;
while (true)
{
if (puzzle[i][pointW] != '*')
{
if (i - 1 < 0 || pointW - 1 < 0)
{
puzzleNum[i][pointW] = num;
num++;
}
else
{
if ((puzzle[i][pointW - 1] == '*') || (puzzle[i - 1][pointW] == '*'))
{
puzzleNum[i][pointW] = num;
num++;
}
}
if (!word.size())
x = puzzleNum[i][pointW];
word.push_back(puzzle[i][pointW]);
pointW++;
//cout << word<<endl;
if (pointW == c)
{
//cout << word << endl;
if(!word.empty())
across.insert({ x,word });
word.clear();
break;
}
}
else
{
//cout << word << endl;
if(!word.empty())
across.insert({ x,word });
word.clear();
pointW++;
if (pointW == c)
break;
}
}
}
//读取纵向单词
for (int i = 0; i < c; i++)
{
word.clear();
int pointW = 0;
while (true)
{
//cout << pointW << endl;
if (puzzle[pointW][i] != '*')
{
if (!word.size())
x = puzzleNum[pointW][i];
word.push_back(puzzle[pointW][i]);
pointW++;
if (pointW == r)
{
down.insert({ x,word });
word.clear();
break;
}
}
else
{
if(!word.empty())
down.insert({ x,word });
word.clear();
pointW++;
if (pointW == r)
break;
}
}
}
print(sum);
}
system("pause");
return 0;
}