1
2
3
4
5 import java.util.*;
6 import java.io.*;
7
8 public class hex
9 {
10 static char[][] hex;
11 static char[] seq;
12 static int nMax;
13
14 static int[][] dc = { {1, 0, -1, -1, -1, 0},
15 {1, 1, 0, -1, 0, 1} };
16 static int[] dr = {0, -1, -1, 0, 1, 1};
17 static char DONE = '\0';
18 static int nSol;
19
20 public static void main(String[] args) throws Exception {
21 String file = (args.length > 0) ? args[0] : "hex.in";
22 Scanner in = new Scanner(new File(file));
23 int r = in.nextInt();
24 while (r > 0) {
25 int c = in.nextInt();
26 hex = new char[r+2][c+3];
27 for (int i = 1; i <= r; i++)
28 for (int j = 1; j <= c + 1 - i % 2; j++)
29 hex[i][j] = in.next().charAt(0);
30 nMax = r*c + r/2;
31 seq = new char[nMax+1];
32 seq[nMax] = '=';
33 nSol = 0;
34 for (int i = 1; i <= r; i++)
35 for (int j = 1; j <= c + 1 - i % 2; j++)
36 if (Character.isDigit(hex[i][j]))
37 solve(i, j, 0, 0);
38 if (nSol == 0)
39 System.out.println("#### NO SOLUTION!");
40 r = in.nextInt();
41 }
42 }
43
44
45
46 static void solve(int r, int c, int n, int nDigits) {
47 char lastCh = hex[r][c];
48 nDigits = Character.isDigit(lastCh) ? nDigits+1 : 0;
49 if (lastCh == DONE || nDigits > 2 ||
50 nDigits == 2 && seq[n-1] == '0')
51 return;
52 seq[n] = lastCh;
53 if (n < nMax - 1) {
54 hex[r][c] = DONE;
55 for (int i = 0; i < 6; i++)
56 solve(r + dr[i], c + dc[r%2][i], n+1, nDigits);
57 hex[r][c] = lastCh;
58 }
59 else if (nDigits > 0)
60 checkEqual();
61 }
62
63 static void checkEqual() {
64
65 int leftExpr = 0;
66 int expr = 0;
67 char lastOp = '+';
68 int digits = 0;
69 for (int i = 0; i <= nMax; i++) {
70 char ch = seq[i];
71 if (Character.isDigit(ch))
72 digits = 10*digits + ch - '0';
73 else {
74 switch(lastOp) {
75 case '+': expr += digits; break;
76 case '-': expr -= digits; break;
77 case '*': expr *= digits; break;
78 case '/': {
79 if (digits == 0 || expr % digits != 0)
80 return;
81 expr /= digits; break;
82 }
83 }
84 digits = 0;
85 if (ch != '=')
86 lastOp = ch;
87 else if (i < nMax) {
88 leftExpr = expr;
89 lastOp = '+';
90 expr = 0;
91 }
92 else if (leftExpr == expr) {
93 nSol++;
94 if (nSol > 1)
95 System.out.print("!!! ");
96 for (int j = 0; j < nMax; j++)
97 System.out.print(seq[j]);
98 System.out.println();
99 }
100 }
101 }
102 }
103 }