您的位置:首页 > 其它

题目1091:棋盘游戏

2014-01-09 21:12 190 查看
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
import java.util.Scanner;
import java.util.Queue;
import java.util.LinkedList;

class Node
{
public int x, y, status;
public int w;

public Node(int x, int y, int w, int status)
{
this.x = x;
this.y = y;
this.w = w;
this.status = status;
}
}

class Main
{
public static final boolean DEBUG = false;
public static int[] dx = {-1, 1, 0, 0};
public static int[] dy = {0, 0, -1, 1};

public static void main(String[] args) throws IOException
{
Scanner cin;
int t;
int[][] grid;
int startx, starty, endx, endy;
int[][][] d;

if (DEBUG) {
cin = new Scanner(new BufferedReader(new FileReader("d:\\OJ\\uva_in.txt")));
} else {
cin = new Scanner(System.in);
}

t = cin.nextInt();

for (int cs = 0; cs < t; cs++) {
grid = new int[6][6];

for (int i = 0; i < 6; i++) {
for (int j = 0; j < 6; j++) {
grid[i][j] = cin.nextInt();
}
}
d = new int[6][6][5];
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 6; j++) {
for (int k = 0; k < 5; k++) {
d[i][j][k] = -1;
}
}
}

startx = cin.nextInt();
starty = cin.nextInt();
endx = cin.nextInt();
endy = cin.nextInt();

d[startx][starty][1] = 0;
Queue<Node> q = new LinkedList<Node>();
Node node = new Node(startx, starty, 0, 1);

q.add(node);
while (!q.isEmpty()) {
node = q.poll();

int x = node.x, y = node.y;
int status = node.status;

for (int i = 0; i < 4; i++) {
int x1 = x + dx[i];
int y1 = y + dy[i];

if (x1 < 0 || x1 >= 6 || y1 < 0 || y1 >= 6) continue;

int cost = status * grid[x1][y1];
int price = d[x][y][status] + cost;
int newStatus = cost % 4 + 1;

if (d[x1][y1][newStatus] == -1 || price < d[x1][y1][newStatus]) {
d[x1][y1][newStatus] = price;
node = new Node(x1, y1, price, newStatus);
q.add(node);
}
}
}

int ans = -1;
for (int i = 1; i <= 4; i++) {
if (d[endx][endy][i] != -1 && (ans == -1 || d[endx][endy][i] < ans)) {
ans = d[endx][endy][i];
}
}

System.out.println(ans);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: