本题有两个坑
第一个坑,一个测试里面有多个测试用例,一直当m和n为-1标识一次测试结束
第二个坑是卡时间,因为有多个测试,就要判断是不是还有输入,hasNest(),这是个阻塞方法,费时,用buffread,用ready()方法,非阻塞方法。
然后就是使用StringBuild类,比arrayList(这个抄袭评论区大佬的)。
再优化使用并行流多线程加快split函数
至于如何顺时针打印,用四条线标识边界,模拟按顺序打印就好了。
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; public class Main { public static void printCirle(int[][] ints, int iBe, int iEn, int jBe, int jEn, StringBuilder sb){ if(iBe == iEn && jBe == jEn){ sb.append(ints[iBe][jBe]).append(","); }else if(iBe == iEn){ for(int i = jBe; i <= jEn; i++){ sb.append(ints[iBe][i]).append(","); } }else if(jBe == jEn){ for(int i = iBe; i <= iEn; i++){ sb.append(ints[i][jBe]).append(","); } }else{ for(int i = jBe; i < jEn; i++){ sb.append(ints[iBe][i]).append(","); } for(int i = iBe; i < iEn; i++){ sb.append(ints[i][jEn]).append(","); } for(int i = jEn; i > jBe; i--){ sb.append(ints[iEn][i]).append(","); } for(int i = iEn; i > iBe; i--){ sb.append(ints[i][jBe]).append(","); } } } public static void main(String[] args) throws IOException{ BufferedReader buffRead = new BufferedReader(new InputStreamReader(System.in)); while (buffRead.ready()) { String[] s = buffRead.readLine().split(" "); int M = Integer.parseInt(s[0]); int N = Integer.parseInt(s[1]); if(M == -1 && N == -1){ break; }else{ StringBuilder stringBuilder = new StringBuilder(); int[][] ints = new int[M][N]; for(int i = 0; i < M; i++){ ints[i] = Arrays.stream(buffRead.readLine().split(" ")).parallel().mapToInt(Integer::parseInt).toArray(); } int iBe = 0, iEn = M - 1, jBe = 0, jEn = N - 1; while (iBe <= iEn && jBe <= jEn) { printCirle(ints, iBe, iEn, jBe, jEn, stringBuilder); iBe++; iEn--; jBe++; jEn--; } System.out.println(stringBuilder.deleteCharAt(stringBuilder.lastIndexOf(",")).toString()); } } } }