这个题容易错,第一点是考虑两种情况,1-n的最短路 对比 1自环和n自环的和,较小的那个就是结果的值。第二点是,求自环的时候,一定要初始化dis[1]为inf,(之前改了很多没用的
东西),第三点,java要使用读入挂, 否则tle
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Main{
static int[] dis,vis,L,head;
static int con,uu,s,e,inf=0x3f3f3f3f,n,m;
static int [][] map;
static class InputReader
{
BufferedReader buf;
StringTokenizer tok;
InputReader()
{
buf = new BufferedReader(new InputStreamReader(System.in));
}
boolean hasNext()
{
while(tok == null || !tok.hasMoreElements())
{
try
{
tok = new StringTokenizer(buf.readLine());
}
catch(Exception e)
{
return false;
}
}
return true;
}
String next()
{
if(hasNext()) return tok.nextToken();
return null;
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
BigInteger nextBigInteger()
{
return new BigInteger(next());
}
BigDecimal nextBigDecimal()
{
return new BigDecimal(next());
}
}
static void djk(int s) {
Queue <Integer>q=new LinkedList<Integer>();
vis=new int[5000];
for(int i=1;i<=n;i++) {
if(i!=s) {
q.add(i);
dis[i]=map[s][i];
vis[i]=0;
}
}
dis[s]=inf;
while(!q.isEmpty()) {
int top = q.poll();
vis[top]=1;
for(int i=1;i<=n;i++) {
if(i==top) continue;
if(dis[i]>dis[top]+map[top][i]) {
dis[i]=dis[top]+map[top][i];
if(vis[i]==1) {
vis[i]=0;
q.add(i);
}
}
}
}
}
public static void main(String[] args) {
InputReader sc = new InputReader();
map=new int [500][500];
dis=new int[500];
while(sc.hasNext()) {
n=sc.nextInt();
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++) {
map[i][j]=sc.nextInt();
}
}
djk(1);
int res1= dis[n];
int res2=dis[1];//1自环
djk(n);
int res3=dis[n];//n自环
System.out.println(Math.min(res1,res2+res3));
}
}
}