String Statistics(2008年珠海市ACM程序设计竞赛)

String Statistics

时间限制(普通/Java):1000MS/3000MS          运行内存限制:65536KByte

描述

 

You have an n × n matrix of lower-case letters. You start from somewhere in the matrix, walk in one of the eight directions (left, right, up, down, up-left, up-right, down-left, down-right) and concatenate every letter you meet, in the order you see them, to form a string. You can stop anywhere (possibly not moving at all!), but you cannot go out of the matrix, or change direction in the middle of the journey.How many different non-empty strings can you get?

 

输入

 

The first line contains t (1 ≤ t ≤ 10), the number of test cases followed. Each test case begins with one integer n(1 ≤ n ≤ 30), followed by n lines, containing the matrix. The matrix will contain lower-case letters only.

 

输出

 

For each test case, print the number of different strings you can get.

 

样例输入

2
2
aa
bb
3
aba
bcc
daa

 

样例输出

6
31
 
题目大意:给出一个n*n的矩阵,有上,下,左,右,左上,左下,右上,右下八个方向,从任意位置开始,按同一方向走动,可以在任意位置停止,输出总共有多少种不为空且各不相同的字符串。
题解:固定方向,用set容器来插入字符串,这样可以去重
#include<iostream>
#include<string>
#include<set>
using namespace std;

int dx[8]={0,0,1,-1,1,1,-1,-1}; //八个方向
int dy[8]={1,-1,0,0,-1,1,-1,1}; int n; char op[40][40]; string str; set<string>p; void dfs(int i,int j,int k) //按同方向搜索
{
if(i>0&&j>0&&i<=n&&j<=n) { str+=op[i][j]; p.insert(str); dfs(i+dx[k],j+dy[k],k); } } int main() { int i,j,k,t; cin>>t; while(t--) { cin>>n; getchar(); for(i=1;i<=n;i++) for(j=1;j<=n;j++) cin>>op[i][j]; p.clear(); //每寻找一次需要清除容器里的东西
    
for(i=1;i<=n;i++) for(j=1;j<=n;j++) for(k=0;k<8;k++)
{
  str
= "";    str+=op[i][j];    p.insert(str);    dfs(i+dx[k],j+dy[k],k); } cout<<p.size()<<endl; } return 0; }

 

posted on 2013-09-13 17:52  落叶伴雨下  阅读(219)  评论(0)    收藏  举报

导航