■1218 Push!!
人の座標と荷物の座標を状態とし,距離を荷物を押した回数としたダイクストラで解ける.- import java.util.*;
- import java.lang.*;
- import java.math.*;
- import java.io.*;
- import static java.lang.Math.*;
- import static java.util.Arrays.*;
- public class Main{
- Scanner sc=new Scanner(System.in);
- int INF=1<<28;
- double EPS=1e-9;
- int m, n;
- int[][] a;
- int mx0, my0, cx0, cy0, gx, gy;
- void run(){
- for(;;){
- m=sc.nextInt();
- n=sc.nextInt();
- if((m|n)==0){
- break;
- }
- a=new int[n][m];
- for(int j=0; j<n; j++){
- for(int i=0; i<m; i++){
- a[j][i]=sc.nextInt();
- if(a[j][i]==2){
- cx0=i;
- cy0=j;
- a[j][i]=0;
- }else if(a[j][i]==3){
- gx=i;
- gy=j;
- a[j][i]=0;
- }else if(a[j][i]==4){
- mx0=i;
- my0=j;
- a[j][i]=0;
- }
- }
- }
- solve();
- }
- }
- void solve(){
- PriorityQueue<P> que=new PriorityQueue<P>();
- boolean[][][][] visited=new boolean[m][n][m][n];
- int[][][][] d=new int[m][n][m][n];
- for(int k=0; k<m; k++){
- for(int j=0; j<n; j++){
- for(int i=0; i<m; i++){
- fill(d[k][j][i], INF);
- }
- }
- }
- que.add(new P(mx0, my0, cx0, cy0));
- visited[mx0][my0][cx0][cy0]=true;
- d[mx0][my0][cx0][cy0]=0;
- int[] dx={0, 0, -1, 1};
- int[] dy={1, -1, 0, 0};
- for(; !que.isEmpty();){
- P p=que.poll();
- if(d[p.mx][p.my][p.cx][p.cy]<p.d){
- continue;
- }
- for(int i=0; i<4; i++){
- P q=new P(p.mx+dx[i], p.my+dy[i], p.cx, p.cy);
- int push=0;
- // 人が画面外or移動不可
- if(q.mx<0||q.mx>=m||q.my<0||q.my>=n||a[q.my][q.mx]==1){
- continue;
- }
- // 人の移動先がブロック
- if(q.mx==q.cx&&q.my==q.cy){
- q.cx+=dx[i];
- q.cy+=dy[i];
- push=1;
- }
- // ブロックが画面外or配置不可
- if(q.cx<0||q.cx>=m||q.cy<0||q.cy>=n||a[q.cy][q.cx]==1){
- continue;
- }
- // 訪問していない
- if(!visited[q.mx][q.my][q.cx][q.cy]){
- q.d=d[q.mx][q.my][q.cx][q.cy]=d[p.mx][p.my][p.cx][p.cy]
- +push;
- visited[q.mx][q.my][q.cx][q.cy]=true;
- que.offer(q);
- }
- }
- }
- int min=INF;
- for(int j=0; j<n; j++){
- for(int i=0; i<m; i++){
- min=min(min, d[i][j][gx][gy]);
- }
- }
- println(""+(min==INF?-1:min));
- }
- class P implements Comparable<P>{
- int mx, my, cx, cy;
- int d;
- P(int mx, int my, int cx, int cy){
- this.mx=mx;
- this.my=my;
- this.cx=cx;
- this.cy=cy;
- }
- @Override
- public int compareTo(P p){
- return d-p.d;
- }
- }
- void debug(Object... os){
- System.err.println(Arrays.deepToString(os));
- }
- void print(String s){
- System.out.print(s);
- }
- void println(String s){
- System.out.println(s);
- }
- public static void main(String[] args){
- // System.setOut(new PrintStream(new BufferedOutputStream(System.out)));
- new Main().run();
- }
- }
0 件のコメント:
コメントを投稿