ter
dsunknown
java
a year ago
1.8 kB
9
Indexable
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Solution {
public static int n, res, sX, sY;
public static int[][] matrix;
public static int[][] visited;
public static int[] moveX = { -1, -1, -1 };
public static int[] moveY = { -1, 0, 1 };
public static boolean quaDuoc;
public static boolean check(int x, int y, int van) {
if (matrix[x][y] == 2 && van == 0) {
return false;
}
return true;
}
public static void backtrack(int x, int y, int coin, int van) {
if (x == 0) {
if (coin > res) {
res = coin;
}
quaDuoc = true;
return;
}
for (int i = 0; i < 3; i++) {
int newX = x + moveX[i];
int newY = y + moveY[i];
if (newX >= 0 && newY >= 0 && newY < 5 && newX<n && check(newX, newY, van)
&& visited[newX][newY] == 0) {
visited[newX][newY] = 1;
int tmp = 0;
if (matrix[newX][newY] == 1) {
tmp = 1;
}
if (matrix[newX][newY] == 2) {
van = van - 1;
}
backtrack(newX, newY, coin + tmp, van);
visited[newX][newY] = 0;
}
}
}
public static void main(String[] args) throws FileNotFoundException {
System.setIn(new FileInputStream("D:/LeCongMinh/B8/QuaCau/sample.txt"));
Scanner sc = new Scanner(System.in);
int tc = sc.nextInt();
for (int t = 1; t <= tc; t++) {
n = sc.nextInt();
matrix = new int[n][5];
visited = new int[n][5];
for (int i = 0; i < n; i++) {
for (int j = 0; j < 5; j++) {
matrix[i][j] = sc.nextInt();
}
}
quaDuoc = false;
res = 0;
backtrack(n, 2, 0, 1);
if(!quaDuoc){
System.out.println("#" + t + " " + -1);
}else{
System.out.println("#" + t + " " + res);
}
}
sc.close();
}
}
Editor is loading...
Leave a Comment