首页 > 解决方案 > 为什么它在 google kickstart 2021 轮 A 测试 2 中出现运行时错误

问题描述

我对编程很陌生,我试图解决这个问题: https ://codingcompetitions.withgoogle.com/kickstart/round/0000000000436140/000000000068cb14 ,这是我的代码:

import java.util.PriorityQueue;
import java.util.Scanner;

class Solution{
    public static void main(String[] args) {
        int[][] dir = new int[][]{{1,0},{-1,0},{0,1},{0,-1}};
        Scanner scan = new Scanner(System.in);
        int t = 0;
        int[][] arr = new int[305][305];
        int row = 0;
        int col = 0;
        PriorityQueue<int[]> pq = new PriorityQueue<int[]>((x,y)->y[0]-x[0]);
        if(scan.hasNextInt())t = scan.nextInt();
        for(int i = 1;i<=t;i++){
            if(scan.hasNextInt())row = scan.nextInt();
            if(scan.hasNextInt())col = scan.nextInt();
            long ans = 0;
            for(int j = 0;j<row;j++){
                for(int k = 0;k<col;k++){
                    if(scan.hasNextInt())arr[j][k] = scan.nextInt();
                    pq.offer(new int[]{arr[j][k],j,k});
                }
            }
            here:
            while(!pq.isEmpty()){
                int[] tmp = pq.poll();
                while(tmp[0]!=arr[tmp[1]][tmp[2]]){
                    tmp = pq.poll();
                    if(pq.isEmpty()&&tmp[0]!=arr[tmp[1]][tmp[2]]){
                        break here;
                    }
                }
                for(int[] x:dir){
                    if(tmp[1]+x[0]<row&&tmp[1]+x[0]>=0&&tmp[2]+x[1]<col&&tmp[2]+x[1]>=0){
                        if(arr[tmp[1]+x[0]][tmp[2]+x[1]]<tmp[0]-1){
                            ans+=tmp[0]-1-arr[tmp[1]+x[0]][tmp[2]+x[1]];
                            arr[tmp[1]+x[0]][tmp[2]+x[1]] = tmp[0]-1;
                            pq.offer(new int[]{tmp[0]-1,tmp[1]+x[0],tmp[2]+x[1]});
                        }
                    }
                }
            }

            System.out.println("Case #"+i+": "+ans);
        }

    }
}

它通过了测试 1,但是在进行测试 2 时,发生了运行时错误。

标签: javaalgorithmruntime-errorjava-11

解决方案


推荐阅读