题目描述
有一个6*6的棋盘,每个棋盘上都有一个数值,现在又一个起始位置和终止位置,请找出一个从起始位置到终止位置代价最小的路径: 1、只能沿上下左右四个方向移动 2、总代价是没走一步的代价之和 3、每步(从a,b到c,d)的代价是c,d上的值与其在a,b上的状态的乘积 4、初始状态为1 每走一步,状态按如下公式变化:(走这步的代价%4)+1。
输入描述:
每组数据一开始为6*6的矩阵,矩阵的值为大于等于1小于等于10的值,然后四个整数表示起始坐标和终止坐标。
输出描述:
输出最小代价。
示例1
输入
复制
1 1 1 1 1 1
1 1 1 1 1 1
1 1 1 1 1 1
1 1 1 1 1 1
1 1 1 1 1 1
1 1 1 1 1 1
0 0 5 5
输出
复制
23
import java.io.*;
import java.util.*;
public class Main
{
private static int[][] direction = {{-1, 0}, {0, -1}, {0, 1}, {1, 0}};
private static int startx;
private static int starty;
private static int endx;
private static int endy;
public static int res;
public static void main(String[] args){
try {
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
int[][] nums = new int[6][6];
for(int i = 0; i < 6; i++) {
String[] parts = br.readLine().split(" ");
for(int j = 0; j < 6; j++) {
nums[i][j] = Integer.parseInt(parts[j]);
}
}
String[] parts = br.readLine().split(" ");
startx = Integer.parseInt(parts[0]);
starty = Integer.parseInt(parts[1]);
endx = Integer.parseInt(parts[2]);
endy = Integer.parseInt(parts[3]);
res = Integer.MAX_VALUE;
boolean[][] visited = new boolean[6][6];
backtrack(nums, visited, startx, starty, 0, 1);
System.out.println(res);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void backtrack(int[][] board, boolean[][] visited, int x, int y, int count, int state) {
if(x == endx && y == endy) {
if(count < res) res = count;
return;
}
if(count >= res) return;
visited[x][y] = true;
for(int i = 0; i < 4; i++) {
int nx = direction[i][0]+x;
int ny = direction[i][1]+y;
if(!inArea(nx,ny) || visited[nx][ny]) continue;
int cur_val = state*board[nx][ny];
backtrack(board, visited, nx, ny, count+cur_val, cur_val%4+1);
}
visited[x][y] = false;
}
private static boolean inArea(int x, int y) {
return (x >= 0 && y >= 0 && x < 6 && y < 6);
}
}