HDU 5612 Baby Ming and Matrix games(dfs搜索） - dblank

# HDU 5612 Baby Ming and Matrix games(dfs搜索）

18
<sum<10
18

3
3 3 24
1*1
+#*
2*8
1 1 1
1
3 3 3
1*0
/#*
2*6

Possible
Possible
Possible

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<map>
#include<cstring>
#include<map>
#include<set>
#include<queue>
#include<stack>
using namespace std;
const int N = 1e2 + 10;
const double eps = 1e-10;
typedef long long ll;
char s[N][N];
int vis[N][N], run[][2] = {2, 0, -2, 0, 0, 2, 0, -2}, ok, m, n;
ll sum;
bool yes(int a,int b)
{
if(a < 1 || a > m || b < 1 || b> n)
return false;
return true;
}
ll gcd(ll a, ll b)
{
return b == 0 ? a : gcd(b, a%b);
}
void dfs(int x, int y, ll fz, ll fm)
{
//cout<<fz <<" "<<fm<<endl;
if(fm / gcd(fz, fm) == 1 && fz/gcd(fz, fm) == sum)
ok = 1;
if(ok) return ;
for(int i = 0; i<4; i++)
{
int a = x + run[i][0];
int b = y + run[i][1];
if(!vis[a][b] && isdigit(s[a][b]) && yes(a, b))
{
int c = (a + x) / 2;
int d = (b + y) / 2;
int num = s[a][b] - '0';
if(s[c][d] == '/' && num == 0)
continue;
vis[a][b] = 1;

if(s[c][d] == '*')
dfs(a, b, fz*num, fm);
else if(s[c][d] == '+')
dfs(a, b, fz+fm*num, fm);
else if(s[c][d] == '-')
dfs(a, b, fz-fm*num, fm);
else if(s[c][d] == '/')
dfs(a,b, fz, fm*num);
vis[a][b] = 0;
}
}
}
int main()
{
int t;
cin>>t;
while(t--)
{
scanf("%d%d%I64d", &m, &n, &sum);
for(int i = 1; i<=m; i++)
for(int j = 1; j<=n; j++)
scanf(" %c", &s[i][j]);
ok = 0;
for(int i = 1; i<=m; i++)
for(int j = 1; j<=n; j++)
{
if(isdigit(s[i][j]))
{
memset(vis, 0, sizeof(vis));
vis[i][j] = 1;
dfs(i, j, s[i][j] - '0', 1);
}
}
if(ok) puts("Possible");
else puts("Impossible");
}
return 0;
}