結果

問題 No.34 砂漠の行商人
ユーザー scache
提出日時 2014-12-01 14:07:58
言語 Java
(openjdk 23)
結果
AC  
実行時間 487 ms / 5,000 ms
コード長 1,704 bytes
コンパイル時間 4,659 ms
コンパイル使用メモリ 79,168 KB
実行使用メモリ 54,732 KB
最終ジャッジ日時 2024-06-28 10:05:35
合計ジャッジ時間 11,906 ms
ジャッジサーバーID
(参考情報)
judge2 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 26
権限があれば一括ダウンロードができます

ソースコード

diff #

import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class Main34 {
	public static void main(String[] args) {
		Main34 p = new Main34();
	}

	public Main34(){
		Scanner sc = new Scanner(System.in);
		int n =sc.nextInt();
		int v =sc.nextInt();
		int sx =sc.nextInt()-1;
		int sy =sc.nextInt()-1;
		int gx =sc.nextInt()-1;
		int gy =sc.nextInt()-1;
		int[][] l = new int[n][n];
		for(int i=0;i<l.length;i++){
			for(int j=0;j<l[i].length;j++)
				l[i][j] = sc.nextInt();
		}
		
		System.out.println(solve(v, sx, sy, gx, gy, l));
	}

	int[] dx = { -1, 0, 1, 0};
	int[] dy = { 0, -1, 0, 1};
	private int solve(int v, int sx, int sy, int gx, int gy, int[][] l) {
		int[][] tl = new int[l.length][l.length];
		for (int i = 0; i < tl.length; i++) {
			Arrays.fill(tl[i], v+1);
		}
		
		LinkedList<Point> queue = new LinkedList<>();
		queue.add(new Point(sx, sy, 0, 0));
				
		while(!queue.isEmpty()){
			Point p = queue.poll();
			
			for(int i=0;i<4;i++){
				int nx = dx[i] + p.x;
				int ny = dy[i] + p.y;
				
				if(nx<0 || l.length<=nx || ny <0 || l.length<=ny)
					continue;
				
				if(nx == gx && ny == gy && v>p.totall+l[ny][nx])
					return p.dist+1;
				
				if(tl[ny][nx] > p.totall+l[ny][nx]){
					tl[ny][nx] = p.totall+l[ny][nx];
					queue.add(new Point(nx, ny, p.totall+l[ny][nx], p.dist+1));
				}
			}
		}
		
		return -1;
		
		
	}

	private class Point{
		int x;
		int y;
		int totall;
		int dist;
		
		public Point(int x, int y, int totall, int dist) {
			this.x = x;
			this.y = y;
			this.totall = totall;
			this.dist = dist;
		}
		
		
	}
	
}
0