# Untitled

unknown
plain_text
a year ago
2.6 kB
2
Indexable
Never
```Picking up Jewels

There is a maze that has one entrance and one exit.
Jewels are placed in passages of the maze.
You want to pick up the jewels after getting into the maze through the entrance and before getting out of it through the exit.
You want to get as many jewels as possible, but you don’t want to take the same passage you used once.

When locations of a maze and jewels are given,
find out the greatest number of jewels you can get without taking the same passage twice, and the path taken in this case.

Time limit : 1 sec (Java : 2 sec)

[Input]
There can be more than one test case in the input file. The first line has T, the number of test cases.
Then the totally T test cases are provided in the following lines (T ≤ 10 )

In each test case,
In the first line, the size of the maze N (1 ≤ N ≤ 10) is given. The maze is N×N square-shaped.
From the second line through N lines, information of the maze is given.
“0” means a passage, “1” means a wall, and “2” means a location of a jewel.
The entrance is located on the upper-most left passage and the exit is located on the lower-most right passage.
There is no case where the path from the entrance to the exit doesn’t exist.

[Output]

Output the greatest number of jewels that can be picked up.

[I/O Example]

Input
2
5
0 0 0 2 0
2 1 0 1 2
0 0 2 2 0
0 1 0 1 2
2 0 0 0 0
6
0 1 2 1 0 0
0 1 0 0 0 1
0 1 2 1 2 1
0 2 0 1 0 2
0 1 0 1 0 1
2 0 2 1 0 0

Output

6
4

Code:
#include<iostream>
using namespace std;
int N;
int map[15][15];
int visit[15][15];
int di[4] = { 0, 0, 1,-1 };
int dj[4] = { 1,-1, 0, 0 };
int ans;
//, tong ;

void reset(){
for(int i =0; i< 15 ; i++){
for(int j=0; j<15; j++){
visit[i][j] =0;
}
}
}

bool checkIn(int i, int j){
if(i >=0 && i < N && j >=0 && j < N) return true;
return false;
}

void backtrack(int i, int j,int tong){
if(i == N-1 && j == N-1){
if(ans < tong ) ans = tong;
return;
}
for(int k =0; k<4; k++){
int i1 = i  + di[k];
int j1 = j  + dj[k];
if(checkIn(i1, j1) && visit[i1][j1] ==0 && map[i1][j1] !=1){
visit[i1][j1] =1;
backtrack(i1, j1, tong + map[i1][j1]/2);
visit[i1][j1] =0;

}
}
}

int main(){
freopen("Text.txt", "r", stdin);
int test;
cin >> test;
for(int tc =1 ; tc <= test ; tc++){
cin >> N;
for(int i =0; i< N ; i++){
for(int j=0; j<N; j++){
cin >> map[i][j];
}
}
ans = 0;
reset();
visit[0][0] =1;
backtrack(0,0,map[0][0]/2);
cout << ans<< endl;
}
return 0;
}```