思路

整体可以分为四个状态,如果按照当前状态行进,下一个块如果不合法,或者已经被走过,则转向。只需要对(2,1)块特判下即可(可以自己模拟一下试试)。


import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    static int n ;
    static int m ;
    static boolean[][] vis;
    static boolean check(int x, int y) {
        return x >= 1 && x <= n && y >= 1 && y <= m;
    }
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (true) {
            n = in.nextInt();
            m = in.nextInt();
            if (n == -1)
                break;
            int[][] map = new int[n + 1][m + 1];
            vis = new boolean[n + 1][m + 1];
            for (int i = 1; i <= n; i++) {
                for (int j = 1 ; j <= m; j++) {
                    map[i][j] = in.nextInt();
                }
            }
            int now = 0;
            int i = 1;
            int j = 1;
            int status = 1;
            while (now < n * m) {
                now ++;
                vis[i][j] = true;
                if (now == n * m) {
                    System.out.print(map[i][j]);
                } else {
                    System.out.print(map[i][j] + ",");
                }
                if (status == 1) {
                    if (!check(i, j + 1) || vis[i][j + 1]) {
                        status = 2;
                        i ++;
                    } else {
                        j ++;
                    }
                } else if (status == 2) {
                    if (!check(i + 1, j) || vis[i + 1][j]) {
                        status = 3;
                        j--;
                    } else {
                        i++;
                    }
                } else if (status == 3) {
                    if (!check(i, j - 1) || vis[i][j - 1]) {
                        status = 4;
                        i--;
                    } else {
                        j--;
                    }
                } else if (status == 4) {
                    if (!check(i - 1, j ) || vis[i - 1][j ]) {
                        status = 1;
                        j++;
                    } else {
                        i--;
                    }
                }
            }
            System.out.println();
        }
    }
}