其他分享
首页 > 其他分享> > 美团笔试 从矩阵起点到终点的最小花费

美团笔试 从矩阵起点到终点的最小花费

作者:互联网

1.第一行输入m,n,k
表示m行n维的数组,k表示接下来有k行数据,如1 1 2 2 1,从(1,1)到(2,2)的费用为1,
求从起点到终点,即(1,1)到(5,4)的最小花费为多少
5 4 3
1 1 2 2 1
1 1 5 4 3
2 2 5 4 1



import java.util.*;
import  java.util.Scanner;
public class fei1 {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int m = in.nextInt();
        int k = in.nextInt();
        int[][] arr = new int[k][5];
        for (int i = 0; i < k; i++) {
            for (int j = 0; j < 5; j++) {
                arr[i][j] = in.nextInt();
            }
        }

        int tempi = 0;
        int tempj = 0;
        int fei = Integer.MAX_VALUE;
        int tempfei = Integer.MAX_VALUE;
        int temp_s = 0;
        int label = 0;
        int[] jilu = new int[k];
        for (int ti = 0; ti < k; ti++) {
            if(jilu[ti]==1)
            {
                continue;
            }
            label = 0;
            for (int i = 0; i < k; i++) {
                if(jilu[i]==1)
                {
                    continue;
                }


                if (arr[i][0] == 1 && arr[i][1] == 1 && label == 0)  {
                    if (arr[i][2] == n && arr[i][3] == m) {
                        tempfei = arr[i][4];
                        fei = Math.min(tempfei, fei);
                        jilu[i] =1;
                        break;
                    } else {


                        tempi = arr[i][2];
                        tempj = arr[i][3];
                        temp_s = arr[i][4];
                        tempfei = arr[i][4];
                        jilu[i] =1;
                        //break;


                    }
                    label = 1;
                } else if ((arr[i][0] == tempi && arr[i][1] == tempj) && (arr[i][2] != n || arr[i][3] != m)) {
                    tempi = arr[i][2];
                    tempj = arr[i][3];
                    temp_s = arr[i][4];
                    tempfei = tempfei + arr[i][4];
                    jilu[i] =1;
                } else if (arr[i][0] == tempi && arr[i][1] == tempj && arr[i][2] == n && arr[i][3] == m) {
                    tempfei = tempfei + arr[i][4];
                    fei = Math.min(tempfei, fei);
                    jilu[i] =1;
                    break;
                }
            }
        }


        if (fei == 0) {
            System.out.println(-1);
        }
        System.out.println(fei);


    }
}















标签:tempfei,arr,int,美团,笔试,矩阵,fei,&&,jilu
来源: https://blog.csdn.net/qq_37602161/article/details/116605720