POJ3050 Hopscotch
题目链接:
POJ3050 Hopscotch
简单理解一下题目:
给定5×5的数组,从任一位置开始,走五步,只能走左下右上四个方向,走过的部分组成一个数字字符串,求一共能产生多少个不同的字符串。
简单分析一下题目:
产生的字符串要是一个个判断是否出现过就很麻烦,这里我们可以用STL里面的set这个数据结构,set是一个集合,里面不会有重复的元素出现,我们只要把所有情况都遍历,然后把生成的所有元素都添加进集合里面,最后输出集合的大小即可。
AC代码:
#include<iostream>
#include<set>
#include<string>
using namespace std;
int a[5][5];
int dx[4] = { -1,0,1,0 };//左下右上四个方向
int dy[4] = { 0,-1,0,1 };
set<string>st;
void dfs(int x, int y, int count, string s) {//count表示还能添加几个字符,s表示当前已经产生的字符串
if (count == 0 && s.length() == 6) {
st.insert(s);
return;
}
while (count) {
for (int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
string ns = s;
if (nx >= 0 && nx < 5 && ny >= 0 && ny < 5) {
ns += ('0' + a[nx][ny]);
dfs(nx, ny, count - 1, ns);
}
}
count--;
}
return;
}
void solve() {
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
string x = "";
x += ('0' + a[i][j]);
dfs(i, j, 5, x);
}
}
cout << st.size() << endl;
return;
}
int main() {
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
cin >> a[i][j];
}
}
solve();
return 0;
}
/*
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 2 1
1 1 1 1 1
*/