Baby Ming and Matrix games
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 849 Accepted Submission(s): 211
Given a n∗m matrix, the character in the matrix(i∗2,j∗2) (i,j=0,1,2...) are the numbers between 0−9. There are an arithmetic sign (‘+’, ‘-‘, ‘∗’, ‘/’) between every two adjacent numbers, other places in the matrix fill with ‘#’.
The question is whether you can find an expressions from the matrix, in order to make the result of the expressions equal to the given integer sum. (Expressions are calculated according to the order from left to right)
Get expressions by the following way: select a number as a starting point, and then selecting an adjacent digital X to make the expressions, and then, selecting the location of X for the next starting point. (The number in same place can’t be used twice.)
In the second line there are two odd numbers n,m, and an integer sum(−1018<sum<1018, divisor 0 is not legitimate, division rules see example)
In the next n lines, each line input m characters, indicating the matrix. (The number of numbers in the matrix is less than 15)
1≤T≤1000
Print Impossible if it is impossible to find such an expressions.
3 3 24
1*1
+#*
2*8
1 1 1
1
3 3 3
1*0
/#*
2*6
Possible
Possible
The first sample:1+2*8=24
The third sample:1/2*6=3
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
using namespace std;
double sum;
int t,n,m,flag;
int vis[][],dir[][]={-,,,,,,,-};
double num[][];
char s[][];
int dfs(int x,int y,double ans)
{
vis[x][y]=;
if(fabs(ans-sum)<=0.000000001)flag=;
for(int i=;i<;i++)
{
int fx=x+dir[i][],fy=y+dir[i][];
int px=x+dir[i][]/,py=y+dir[i][]/;
if(fx>=&&fx<=n&&fy<=m&&fy>=&&vis[fx][fy]==&&s[fx][fy]!='#')
{
if(s[px][py]=='+')
dfs(fx,fy,ans+num[fx][fy]);
else if(s[px][py]=='*')
dfs(fx,fy,ans*num[fx][fy]);
else if(s[px][py]=='-')
dfs(fx,fy,ans-num[fx][fy]);
else if(s[px][py]=='/'&&num[fx][fy]!=)
dfs(fx,fy,ans/num[fx][fy]);
}
}
vis[x][y]=;
return;
}
int main()
{
scanf("%d",&t);
while(t--)
{
flag=;
memset(vis,,sizeof(vis));
memset(num,-,sizeof(num));
scanf("%d%d%lf",&n,&m,&sum);
for(int i=;i<=n;i++)
{
scanf("%s",s[i]+);
}
for(int i=;i<=n;i++)
{
for(int j=;j<=m;j++)
{
if(s[i][j]>='0'&&s[i][j]<='9')
{
num[i][j]=s[i][j]-'0';
}
}
}
for(int i=;i<=n;i++)
{
for(int j=;j<=m;j++)
{
if(s[i][j]>='0'&&s[i][j]<='9')
{
dfs(i,j,num[i][j]);
}
}
}
if(flag)printf("Possible\n");
else printf("Impossible\n");
}
return;
}