首页 > 试题广场 >

顺时针打印数字矩阵

[编程题]顺时针打印数字矩阵
  • 热度指数:4614 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
给定一个数字矩阵,请设计一个算法从左上角开始顺时针打印矩阵元素

输入描述:
输入第一行是两个数字,分别代表行数M和列数N;接下来是M行,每行N个数字,表示这个矩阵的所有元素;当读到M=-1,N=-1时,输入终止。


输出描述:
请按逗号分割顺时针打印矩阵元素(注意最后一个元素末尾不要有逗号!例如输出“1,2,3”,而不是“1,2,
3,”),每个矩阵输出完成后记得换行
示例1

输入

3 3
1 2 3
4 5 6
7 8 9
-1 -1

输出

1,2,3,6,9,8,7,4,5

备注:
M,N为正整数且 M*N<=300000
#include <bits/stdc++.h>
using namespace std;
const int N = 1050;

int n, m;
int a[N][N], ans[N][N];
bool vis[N][N];

vector<int>v;

int dx[] = {0, 1, 0, -1};
int dy[] = {1, 0, -1, 0};

void dfs(int x, int y, int dirx, int diry) {
    v.push_back(a[x][y]);
    vis[x][y] = 1;
    int xx = x + dirx, yy = y + diry;
    if (xx >= 1 && xx <= n && yy >= 1 && yy <= m && !vis[xx][yy])
        dfs(xx, yy, dirx, diry);
    for (int i = 0; i < 4; ++i) {
        int xx = x + dx[i], yy = y + dy[i];
        if (xx >= 1 && xx <= n && yy >= 1 && yy <= m && !vis[xx][yy]) {
            dfs(xx, yy, dx[i], dy[i]);
        }
    }
}

int main() {
    while (cin >> n >> m) {
        if (n == -1 && m == -1) break;
        for (int i = 1; i <= n; ++i)
            for (int j = 1; j <= m; ++j)
                cin >> a[i][j];
        v.clear();
        memset(vis, 0, sizeof vis);
        dfs(1, 1, 0, 1);
        for (int i = 0; i < v.size() - 1; ++i)
            cout << v[i] << ',';
        cout << v[v.size() - 1] << '\n';
    }
}
发表于 2019-10-14 22:02:24 回复(0)
语言:Python 3 运行时间: 168 ms 占用内存:19336K 状态:答案正确

while 1:
    m,n = map(int,input().split())
    if m == -1: break
    p = []
    o = [input().split() for _ in range(m)]
    while 1:
        try:
            p.extend(o.pop(0))
            for i in range(len(o)-1):
                p.append(o[i].pop())
            p.extend(o.pop(-1)[::-1])
            for i in range(-len(o)+1,0):
                p.append(o[-i].pop(0))
        except: break
    print(','.join(p))

编辑于 2019-09-13 22:52:49 回复(0)

Python Solution

def clock_print(matrix):
    c = []
    while True:
        try:
            c.extend(matrix.pop(0))
            for i in range(len(matrix)-1):
                c.append(matrix[i].pop())
            c.extend(matrix.pop(-1)[::-1])
            for i in range(-len(matrix)+1,0):
                c.append(matrix[-i].pop(0))
        except IndexError:
            break
    return c

while True:
    M,N = [int(i) for i in input().split()]
    if M==-1 and N==-1:
        break
    matrix = [[str(i) for i in input().split()] for m in range(M)]
    result = clock_print(matrix)
    print(','.join(result))
编辑于 2019-08-29 11:39:10 回复(0)
利用模拟边界法求解
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String str;
        while((str = br.readLine()) != null){
            String[] strNums = str.split(" ");
            int m = Integer.parseInt(strNums[0]), n = Integer.parseInt(strNums[1]);
            if(m == -1 || n == -1) break;
            int[][] matrix = new int[m][n];
            for(int i = 0; i < m; i++){
                String[] row = br.readLine().trim().split(" ");
                for(int j = 0; j < n; j++)
                    matrix[i][j] = Integer.parseInt(row[j]);
            }
            System.out.println(solve(matrix, m, n));
        }
    }
    
    // 模拟边界法
    private static String solve(int[][] matrix, int m, int n) {
        StringBuilder sb = new StringBuilder();
        int left = 0, right = n - 1, top = 0, bottom = m - 1;
        int start = 0, end = m * n;
        while(start < end) {
            for(int i = left; i <= right; i++){
                sb.append(matrix[top][i]).append(",");
                start ++;
            }
            top ++;
            if(top > bottom) break;
            for(int i = top; i <= bottom; i++){
                sb.append(matrix[i][right]).append(",");
                start ++;
            }
            right --;
            if(right < left) break;
            for(int i = right; i >= left; i--){
                sb.append(matrix[bottom][i]).append(",");
                start ++;
            }
            bottom --;
            if(bottom < top) break;
            for(int i = bottom; i >= top; i--){
                sb.append(matrix[i][left]).append(",");
                start ++;
            }
            left ++;
            if(left > right) break;
        }
        sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }
}


发表于 2020-10-26 11:28:25 回复(0)
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
const int N = 1050;
int g[N][N];
bool st[N][N];
int m, n;

int main()
{
    while (cin >> m >> n)
    {
        memset(g, 0, sizeof(g));
        memset(st, 0, sizeof(st));
        if (m == -1 && n == -1) break;
        for (int i = 0; i < m; i++)
            for (int j = 0; j < n; j++)
                cin >> g[i][j];
        int dx[] = { 0, 1, 0, -1 }, dy[] = { 1, 0, -1, 0 };

        for (int i = 0, j = 0, k = 1, d = 0; k <= n * m; k++)
        {
            if (i != 0 || j != 0) cout << ',';
            cout << g[i][j];
            st[i][j] = true;
            int a = i + dx[d], b = j + dy[d];
            if (a < 0 || a >= m || b < 0 || b >= n || st[a][b])
            {
                d = (d + 1) % 4;
                a = i + dx[d], b = j + dy[d];
            }
            i = a, j = b;
        }
        cout << endl;
    } 
    return 0;
}
发表于 2020-06-09 11:11:32 回复(0)
/*
offer原题:
https://www.nowcoder.com/practice/9b4c81a02cd34f76be2659fa0d54342a?tpId=13&tqId=11172&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking


*/

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        while(br.ready()) {
            String[] s = br.readLine().split(" ");
            int m = Integer.parseInt(s[0]);
            int n = Integer.parseInt(s[1]);
            if(m == -1 && n == -1) break;
            int[][] matrix = new int[m][n];
            for(int i = 0; i < m; i++) {
                String[] temp = br.readLine().split(" ");
                for(int j = 0; j < n; j++)
                    matrix[i][j] = Integer.parseInt(temp[j]);
            }
            printMatrix(matrix, m, n);
        }
    }
    public static void printMatrix(int[][] matrix,int row,int col) {
        //创建StringBuffer存储,因为有,号
        StringBuilder sb = new StringBuilder();
        if(matrix==null || row == 0 || col == 0)return;
        //记录圈数
        int start = 0;
        //其他人的方法
        start = (Math.min(col,row)-1)/2+1;//确定需要的层数
        for(int i = 0;i < start;i++){
            //从左到右打印
            for(int k = i;k<col-i;k++) 
                sb.append(matrix[i][k]+",");;
            //从右上到右下
            for(int j=i+1;j<row-i;j++) 
                sb.append(matrix[j][col-i-1] + ",");
            //从右到左
            for(int k=col-i-2;(k>=i)&&(row-i-1!=i);k--)
                sb.append(matrix[row-i-1][k] + ",");
            //从左下到左上
            for(int j=row-i-2;(j>i)&&(col-i-1!=i);j--)
                sb.append(matrix[j][i] + ",");
        }
        //输出,记得去掉最后一个“,”
        System.out.println(sb.substring(0,sb.length()-1));
    }
}

发表于 2020-05-24 12:19:28 回复(0)
import java.util.*;
public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int m = sc.nextInt();
        int n = sc.nextInt();
        while(m!=-1&n!=-1){
            int[][] matrix=new int[m][n];
            for(int i =0;i<m;i++){
                for(int j=0;j<n;j++){
                    matrix[i][j]=sc.nextInt();
                }
            }
            ArrayList<Integer> list = printMatrix(matrix);
            for(int i=0;i<list.size();i++) {
            if(i==list.size()-1) {
                System.out.println(list.get(i));
            }else {
                System.out.print(list.get(i)+",");
            }
        }
            m=sc.nextInt();
            n=sc.nextInt();
        }
    }
       public static ArrayList<Integer> printMatrix(int [][] matrix) {
       ArrayList<Integer> list = new ArrayList<>();
       if(matrix == null||matrix.length==0 || matrix[0].length==0 )
           return list;
        int up = 0;
        int down = matrix.length-1;
        int left = 0;
        int right = matrix[0].length-1;
        while(true){
            for(int col=left;col<=right;col++){
                list.add(matrix[up][col]);
            }
            up++;
            if(up>down){
                break;
            }
            for(int lie=up;lie<=down;lie++){
                list.add(matrix[lie][right]);
            }
            right--;
            if(right<left)
                break;
            for(int col=right;col>=left;col--){
                list.add(matrix[down][col]);
            }
            down--;
            if(down<up)
                break;
            for(int row=down;row>=up;row--){
                list.add(matrix[row][left]);
            }
            left++;
            if(left>right)
                break;
        }
            return list;
    }
}

发表于 2020-02-29 00:10:02 回复(1)
#include <bits/stdc++.h>
using namespace std;

int main(){
    int n,m;
    while(cin>>m>>n){
        if(m==-1 && n==-1)
            break;
        int a[m][n],left=0,top=0,right=n-1,down=m-1;
        for(int i=0;i<m;i++)
            for(int j=0;j<n;j++)
                cin>>a[i][j];
        vector<int> v;
        while(left<=right && top<=down){
            for(int j=left;j<=right;j++)
                v.push_back(a[top][j]);
            top++;
            for(int i=top;i<=down;i++)
                v.push_back(a[i][right]);
            right--;
            for(int j=right;j>=left && top<=down;j--)
                v.push_back(a[down][j]);
            down--;
            for(int i=down;i>=top && left<=right;i--)
                v.push_back(a[i][left]);
            left++;
        }
        for(int i=0;i<v.size();i++){
            if(i==v.size()-1)
                cout<<v[i]<<endl;
            else
                cout<<v[i]<<",";
        }
    }
    return 0;
}

发表于 2019-10-06 00:18:18 回复(0)
从(0,0)开始往右走,超出边界或已经访问过了,切换方向往下走,同样超出边界或已经访问过了,切换方向往左走,继续超出边界或已经访问过了,切换方向往上走。。。。直到连续切换2方向以上,就到终点了。
#include<iostream>
using namespace std;
  
int main(){
    int N,M;
    //首次输入N,M
    cin>>N>>M;
    //判断N,M是否满足条件
    while(N!=-1 && M!=-1){
        int arr[N][M];
        //输入方阵
        for(int i=0;i<N;i++)
            for(int j=0;j<M;j++)
                cin>>arr[i][j];
        //开始螺旋形输出
        {
            //定义四个方向,顺序为右,下,左,上
            int directions[4][2]={{0,1},{1,0},{0,-1},{-1,0}};
            //定义记录访问矩阵,初始值为0,访问后为1
            int visited[N][M];
            for(int i=0;i<N;i++)
                for(int j=0;j<M;j++)
                    visited[i][j]=0;
            //定义初始位置(0,0)
            int i=0,j=0;
            //定义初始方向为向右,即direct=0
            int direct=0;
            //定义标记符,每切换一次方向就加1,只要能继续下一步就置0
            int flag=0;
            //开始循环
            while(1){
                //尝试过2个方向,即无路可走,终结
                if(flag==2)
                    break;
                //访问当前位置的值,并记录为已访问
                cout<<arr[i][j];
                visited[i][j]=1;
                //探索方向
                while(1){
                    //尝试过2个方向,即无路可走,终结
                    if(flag==2)
                        break;
                    //计算下一步的坐标
                    int new_i=i+directions[direct][0];
                    int new_j=j+directions[direct][1];
                    //判断下一步坐标是否满足在方阵范围内,是否未访问
                    if(new_i>=0 && new_i<N && new_j>=0 && new_j<M && visited[new_i][new_j]==0){
                        //将满足条件的新坐标赋给i,j
                        i=new_i;
                        j=new_j;
                        //当前方向可以继续下一步,flag置0
                        flag=0;
                        //输出逗号,
                        cout<<',';
                        break;
                    }
                    //不满足上个条件,需要切换方向,并且flag+1
                    else{
                        //切换方向
                        direct=(direct+1)%4;
                        flag+=1;
                    }
                }
            }
        }
        cout<<endl;
        cin>>N>>M;
    }
    return 0;
}


发表于 2019-08-20 10:20:42 回复(0)
//Java AC 100%
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        while(br.ready()) {
            String[] s = br.readLine().split(" ");
            int m = Integer.parseInt(s[0]);
            int n = Integer.parseInt(s[1]);
            if(m == -1 && n == -1) break;
            int[][] matrix = new int[m][n];
            for(int i = 0; i < m; i++) {
                String[] temp = br.readLine().split(" ");
                for(int j = 0; j < n; j++)
                    matrix[i][j] = Integer.parseInt(temp[j]);
            }
            printMatrix(matrix, m, n);
        }
    }
    private static void printMatrix(int[][] mat, int rows, int cols) {
        if(mat == null || rows == 0 || cols == 0) return;
        StringBuilder sb = new StringBuilder();
        int min = Math.min(rows, cols);
        for(int s = 0; 2*s < min; s++) {
            int endRow = rows-1-s;
            int endCol = cols-1-s;
            for(int j = s; j <= endCol; j++) //直接打印第一行
                sb.append(mat[s][j]+",");
            if(endRow > s) { //存在第二行的条件
                for(int i = s+1; i <= endRow; i++)
                    sb.append(mat[i][endCol]+",");
                if(endCol > s) { //存在第三行的条件
                    for(int j = endCol-1; j >= s; j--)
                        sb.append(mat[endRow][j]+",");
                    if(endRow > s+1) { //存在第四行的条件
                        for(int i = endRow-1; i > s; i--)
                            sb.append(mat[i][s]+",");
                    }
                }
            }
        }
        //打印
        System.out.println(sb.substring(0,sb.length()-1));
    }
}

编辑于 2019-08-19 17:04:27 回复(0)
#include<bits/stdc++.h>
using namespace std;
int main()
{
    int m,n;
    while(cin>>m>>n)
    {
        if(m==-1&&n==-1)
            break;
        vector<vector<int>>num(m,vector<int>(n));
        for(int i=0;i<m;i++)
            for(int j=0;j<n;j++)
                cin>>num[i][j];
        int up=0,down=m-1,left=0,right=n-1;
        cout<<num[0][0];
        while(left<=right&&up<=down)
        {
            if(left==right)
            {
                for(int i=up;i<=down;i++)
                {
                    if(!(left==0&&i==0))
                        cout<<","<<num[i][left];
                }
            }
            else if(up==down)
            {
                for(int i=left;i<=right;i++)
                    if(!(up==0&&i==0))
                        cout<<","<<num[up][i];
            }
            else
            {
                for(int i=left;i<right;i++)
                    if(!(up==0&&i==0))
                        cout<<","<<num[up][i];
                for(int i=up;i<down;i++)
                    if(!(right==0&&i==0))
                        cout<<","<<num[i][right];
                for(int i=right;i>left;i--)
                    if(!(down==0&&i==0))
                        cout<<","<<num[down][i];
                for(int i=down;i>up;i--)
                    if(!(left==0&&i==0))
                        cout<<","<<num[i][left];
            }
            up++;
            down--;
            left++;
            right--;
        }
        cout<<endl;
    }
    return 0;
}

发表于 2019-08-13 20:02:22 回复(0)
def rotate(matrix):
    """
    逆时针旋转矩阵
    :param matrix:
    :return:
    """
    return list(zip(*matrix))[::-1]

def print_matrix(matrix):
    """
    删除第一行,剩下的矩阵逆时针旋转
    :param m:
    :param n:
    :param matrix:
    :return:
    """
    res = []
    while matrix:
        cur = matrix.pop(0)
        res += [x for x in cur]
        matrix = rotate(matrix)
    print(','.join([str(x) for x in re***atrix = [[1,2,3],[4,5,6],[7,8,9]]
# print_matrix(matrix)

while True:
    matrix = []
    m, n = list(map(int, input().split()))
    if m==-1 and n==-1:
        break
    for i in range(m):
        matrix.append(list(map(int, input().split())))
    print_matrix(matrix)
 

发表于 2019-05-19 01:20:31 回复(1)
'''
思路:先取矩阵的第一行,接着将剩下作为新矩阵进行一个逆时针90度的翻转,接着获取第一行,直到矩阵为空。
'''
def printMatrix(matrix):
    result=[]
    while(matrix):
        result+=matrix.pop(0)
        if not matrix or not matrix[0]:
            break
        matrix=turn(matrix)
    print(result)

def turn(matrix):
    nrow=len(matrix)
    ncol=len(matrix[0])
    newMatrix=[]
    for i in range(ncol):
        ***=[]
        for j in range(nrow):
            ***.append(matrix[j][i])
        newMatrix.append(***)
    newMatrix.reverse()
    return newMatrix

发表于 2019-05-15 20:34:47 回复(0)
//此为一个笨办法
//先以(优先级:右下左上)运动;
//然后打一个补丁:当运动到一个方向时,优先按照该方向运动
//(笑)

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    static StringBuilder pt = new StringBuilder();
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextInt()) { // 注意 while 处理多个 case
            int m = in.nextInt();
            int n = in.nextInt();
            if (m == -1 && n == -1) {
                break;
            }
            //存储
            int[][] num = new int[m][n];
            for (int i = 0 ; i < m ; i++) {
                for (int j = 0 ; j < n ; j++) {
                    num[i][j] = in.nextInt();
                }
            }

            //当前要输出的坐标
            int x = 0, y = 0;
            //adws,控制方向
            char direction = 'd';
            do {
                pt.append(num[x][y]);
                num[x][y] = -1;

                //优先沿袭之前的方向
                if ('d' == direction || 'a' == direction){
                    int size = fixLeftRight(num, x, y, m, n);
                    if (size == 0){
                        
                    }else{
                        y += size;
                        continue;
                    }
                }else{
                    int size = fixUpDown(num, x, y, m, n);
                    if (size == 0){
                        
                    }else{
                        x += size;
                        continue;
                    }
                }
                
                //开始转向
                //将-1作为结束标志,输出后数据转为-1
                if (y + 1 != n && num[x][y + 1] != -1) {
                    y++;direction = 'd';
                    pt.append(",");
                } else if (x + 1 != m && num[x + 1][y] != -1 ) {
                    x++;direction = 's';
                    pt.append(",");
                } else if (y != 0 && num[x][y - 1] != -1) {
                    y--;direction = 'a';
                    pt.append(",");
                } else if (x != 0 && num[x - 1][y] != -1) {
                    x--;direction = 'w';
                    pt.append(",");
                } else {
                    System.out.println(pt.toString());
                    pt = new StringBuilder();
                    break;
                }
            } while (true);

        }
    }

    public static int fixUpDown(int[][] num, int x, int y, int m, int n) {
        if (x + 1 != m && num[x + 1][y] != -1 ) {
            pt.append(",");
            return 1;
        }
        if (x != 0 && num[x - 1][y] != -1) {
            pt.append(",");
            return -1;
        }
        return 0;
    }

    public static int fixLeftRight(int[][] num, int x, int y, int m, int n) {
        if (y + 1 != n && num[x][y + 1] != -1) {
            pt.append(",");
            return 1;
        }
        if (y != 0 && num[x][y - 1] != -1) {
            pt.append(",");
            return -1;
        }

        return 0;
    }
}

发表于 2023-11-22 12:00:37 回复(0)
package main

import(
    "fmt"
    "strings"
    "strconv"
    "os"
    "bufio"
)

var r *bufio.Reader
var rowLen, colLen int


func printM(m [][]int) {
    
//     矩阵外圈一层框架遍历
    rows, rowe, cols, cole := 0, rowLen-1, 0, colLen-1
    for rows<= rowe&&cols<=cole{
        for i:=cols; i<=cole; i++{
            if i == 0{fmt.Print(m[cols][i])}else{fmt.Print(",",m[cols][i])}
        }
        for i:=rows+1; i<=rowe; i++{
            fmt.Print(",",m[i][cole])
        }
        for i:=cole-1; i>=cols&&rowe!=rows; i--{
            fmt.Print(",",m[rowe][i])
        }
        for i:=rowe-1; i>rows&&cole!=cols; i--{
            fmt.Print(",",m[i][cols])
        }
        
        rows++
        rowe--
        cols++
        cole--
    }
    fmt.Println()
}


// 以split字符分割标准输入的字串
func splitStdString(split byte) string{
	text,_ := r.ReadString(split)
	text = strings.Trim(text, string(split))
	return text
}

func main() {
    r = bufio.NewReader(os.Stdin)

    for {
        matrixLen := splitStdString('\n')
        rc := strings.Split(matrixLen, " ")
        if matrixLen == "-1 -1"{
            break
        }
        rowLen, _ = strconv.Atoi(rc[0]) 
        colLen, _ = strconv.Atoi(rc[1]) 
//         开辟矩阵
        m := make([][]int, rowLen)
        for i:= 0; i<rowLen; i++{
            m[i] = make([]int, colLen)
        }
        var numStr string
        var numByte []string
        for i:=0; i<rowLen;i++{
            numStr = splitStdString('\n')
            numByte = strings.Split(numStr, " ")
            for j:=0; j<colLen; j++{
                m[i][j],_ = strconv.Atoi(numByte[j])
            }
        }
//         fmt.Println(m)
        printM(m)
    }
}

发表于 2021-09-20 18:15:36 回复(0)
#include <bits/stdc++.h>
using namespace std;
int main(){
    int row, col;
    while(cin>>row>>col){
        if(row==-1) break;
        vector<vector<int>> matrix(row, vector<int>(col));
        for(int i=0; i<row; ++i){
            for(int j=0; j<col; ++j){
                cin>>matrix[i][j];
            }
        }
        int left = 0, right = col-1;
        int top = 0, bot = row-1;
        vector<int> ans;
        while(left<=right && top <= bot){
            for(int i=left; i<=right; ++i){
                ans.push_back(matrix[top][i]);
            }
            for(int i=top+1; i<bot; ++i){
                   ans.push_back(matrix[i][right]); 
            }
            if(bot > top){
                for(int i=right; i>=left; --i){
                    ans.push_back(matrix[bot][i]);
                }
            }
            if(left < right){
                for(int i=bot-1; i>top; --i){
                   ans.push_back(matrix[i][left]); 
                }
            }
            left++; right--;
            top++; bot--;
        }
        cout<<ans[0];
        for(int i=1; i<ans.size(); ++i){
            cout<<","<<ans[i];
        }
        cout<<endl;
    }
    return 0;
}

发表于 2020-07-29 16:32:10 回复(0)
四个指针,剑指offer原题
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
 
/**
 * @Author: coderjjp
 * @Date: 2020-05-07 15:02
 * @Description:
 * @version: 1.0
 */
public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String str;
        while (!(str = br.readLine()).equals("-1 -1")){
            String[] s = str.split(" ");
            int m = Integer.valueOf(s[0]);
            int n = Integer.valueOf(s[1]);
            int arr[][] = new int[m][n];
            for (int i = 0; i < m; i++){
                s = br.readLine().split(" ");
                for (int j = 0; j < n; j++)
                    arr[i][j] = Integer.valueOf(s[j]);
            }
 
            int l=0, r=n-1, t=0, b=m-1;
            StringBuilder sb = new StringBuilder();
            while (l<=r && t<=b){
                for (int i=l;i<=r;i++)
                    sb.append(arr[t][i]).append(",");
                t++;
                if (t>b)
                    break;
                for (int i=t;i<=b;i++)
                    sb.append(arr[i][r]).append(",");
                r--;
                if (l>r)
                    break;
                for (int i=r;i>=l;i--)
                    sb.append(arr[b][i]).append(",");
                b--;
                if (t>b)
                    break;
                for (int i=b;i>=t;i--)
                    sb.append(arr[i][l]).append(",");
                l++;
                if (l>r)
                    break;
            }
            System.out.println(sb.deleteCharAt(sb.length()-1));
        }
    }
}


发表于 2020-05-07 15:24:03 回复(0)
package com.itranswarp.learnjava;

import java.util.*;

public class test2 {
    static int [][] biaoji=new int[100][100];
    static  int [][] intA=new int[100][100];
    static List<String> list1=new ArrayList<>();
    public static void main(String[] args){
        Scanner cin = new Scanner(System.in);
        int m, n;
        while(true) {
            list1.clear();
            String[] stre=cin.nextLine().split(" ");
            m = Integer.parseInt(stre[0]);
            n = Integer.parseInt(stre[1]);
            if (m == -1 && n == -1) {
                break;
            }
            for (int i = 0; i < m; i++) {
                String[] arr = cin.nextLine().split(" ");
                for (int j = 0; j < n; j++) {
                    intA[i][j] = Integer.parseInt(arr[j]);
                }
            }
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++) {
                    biaoji[i][j] = 0;
                }
            }
            int fangxiang = 0;
            test(0, 0, 0,m,n);
            String sss=String.join(",",list1);
            System.out.println(sss);


        }
}
    public static boolean isall(int[][] aa,int m,int n){
        int num=0;
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                if(aa[i][j]==0){
                    num=1;
                    break;
                }
            }
        }
        if(num==1){
            return true;
        }
        else {
            return false;
        }
    }
    public static  void test(int x,int y,int fangxiang,int m,int n){
        if(fangxiang==0){
            if(x!=0 || y!=0  ){ y++;}

            while ( y<n && biaoji[x][y]==0 ){
                list1.add(Integer.toString(intA[x][y]));
                biaoji[x][y]=1;
                y++;
            }
            if(isall(biaoji,m,n)){
                test(x, y-1, 1,m,n);
            }

        }
        else if(fangxiang==1){
            x++;
            while(x<m  && biaoji[x][y]==0 ){
                list1.add(Integer.toString(intA[x][y]));
                biaoji[x][y]=1;
                x++;
            }
            if(isall(biaoji,m,n)){
                test(x-1, y, 2,m,n);
            }

        }
        else if(fangxiang==2){
            x--;
            while ( x>=0 && biaoji[x][y]==0 ){
                list1.add(Integer.toString(intA[x][y]));
                biaoji[x][y]=1;
                x--;
            }
            if(isall(biaoji,m,n)){
                test(x+1, y, 3,m,n);
            }

        }
        else if(fangxiang==3){
            y--;
            while ( y>=0 && biaoji[x][y]==0 ){
                list1.add(Integer.toString(intA[x][y]));
                biaoji[x][y]=1;
                y--;
            }
            if(isall(biaoji,m,n)){
                test(x, y+1, 0,m,n);
            }

        }
    }
}

发表于 2020-04-04 18:33:37 回复(0)
TER头像 TER
60% 通过率
while True:
    m,n = map(int,input().strip().split(" "))
    if m == -1:break
    L = []
    for row in range(m):
        L.append(list(map(int,input().strip().split(" "))))
    # 输出最外层
    def clockPrint(L):
        if L == []:
            return []   
        m,n = len(L), len(L[0])
        if m == 1:
            return L[0]
        if n == 1:
            ans = [i[0] for i in L]
            return ans

        res = L[0]
        for i in range(1,m-1):
            res.append(L[i][n-1])
        res = res + L[-1][::-1]
        for i in range(m-2,0,-1):
            res.append(L[i][0])
        sub_L = [j[1:n-1] for j in L[1:m-1]]
        res = res + clockPrint(sub_L)
        return res
    ans = str(clockPrint(L))[1:-1].replace(", ", ",")
    print(ans)


发表于 2020-04-01 13:26:32 回复(0)
旋转矩阵
def traverse(matrix):
    m=len(matrix)
    n=len(matrix[0])
    new_matrix=[]
    for i in range(n):
        new_matrix1=[]
        for j in range(m):
            new_matrix1.append(matrix[j][i])
        new_matrix.append(new_matrix1)
    new_matrix.reverse()
    return new_matrix
返回输出
def printmatrix(matrix):
    array=[]
    while matrix:
        for item in matrix[0]:
            array.append(item)
        del matrix[0]
        if len(matrix)==0:
            break
        matrix=traverse(matrix)
    return array
while True:
    m,n=[int(x) for x in input().split()]
    if m==-1&nbs***bsp;n==-1:
        break
    matrix = [[int(x) for x in input().split()] for j in range(m)]
    result=printmatrix(matrix)
    print(','.join(map(str,result)))
您的代码已保存
运行超时:您的程序未能在规定时间内运行结束,请检查是否循环有错或算法复杂度过大。点击对比用例标准输出与你的输出
case通过率为86.67%
就酱~这个是我自己能理解的写法,比起大佬是真的复杂,主要用了之前看到的顺时针打印矩阵的解法

发表于 2020-03-20 16:18:43 回复(0)

热门推荐

通过挑战的用户

查看代码
顺时针打印数字矩阵