此题先读取二维方格,然后遍历数组找到所有起始格存在另一个数组中,最后分别对数组进行行、列遍历,找到每行、列的所有‘单词’,注意对于列扫描的默认顺序不是从小到大的,要另外开一个数组存放起始格标号,然后把‘单词’放在数组中,最后进行排序,输出所有‘单词’。
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
const int maxn = 12;
int input[maxn][maxn];
int weight[maxn][maxn];
char down_buf[45][maxn];
int down_key[45];
bool cmp(int a,int b)
{
return a<b;
}
int main()
{
int r,c;
int puzzle = 0;
while(~scanf("%d",&r)&&r)
{
memset(weight,0,sizeof(weight));
scanf("%d",&c);
getchar();
for(int i=0; i<r; i++)
{
for(int j=0; j<c; j++)
input[i][j] = getchar();
getchar();
}
int count_space = 0;
for(int i=0; i<r; i++)
{
for(int j=0; j<c; j++)
{
if(input[i][j] == '*'){weight[i][j] = -1;continue;}
if(i==0 || j==0)weight[i][j] = ++count_space;
else if(input[i][j-1]=='*' || input[i-1][j]=='*')
weight[i][j] = ++count_space;
}
}
if(puzzle>0)putchar('\n');
//row
printf("puzzle #%d:\n",++puzzle);
printf("Across\n");
for(int i=0; i<r; i++)
{
int row_index = 0;
while(row_index<c)
{
if(input[i][row_index] == '*')
{
row_index++;continue;
}
printf("%3d.",weight[i][row_index]);
while(input[i][row_index]!='*' && row_index<c)
{
putchar(input[i][row_index]);
row_index++;
}
putchar('\n');
}
}
printf("Down\n");
int key = 0;
for(int j=0; j<c; j++)
{
int column_index = 0;
while(column_index<r)
{
if(input[column_index][j] == '*')
{
column_index++;continue;
}
//printf("%3d.",weight[column_index][j]);
down_key[key] = weight[column_index][j];
int k = 0;
while(input[column_index][j]!='*' && column_index<r)
{
//putchar(input[column_index][j]);
down_buf[down_key[key]][k++] = input[column_index][j];
column_index++;
}
down_buf[down_key[key]][k] = 0;
//putchar('\n');
key++;
}
}
sort(down_key,down_key+key,cmp);
for(int i=0; i<key; i++)
{
printf("%3d.",down_key[i]);
printf("%s\n",down_buf[down_key[i]]);
}
}
return 0;
}