输入第一行是两个数字,分别代表行数M和列数N;接下来是M行,每行N个数字,表示这个矩阵的所有元素;当读到M=-1,N=-1时,输入终止。
请按逗号分割顺时针打印矩阵元素(注意最后一个元素末尾不要有逗号!例如输出“1,2,3”,而不是“1,2,
3,”),每个矩阵输出完成后记得换行
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'; } }
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))
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))
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(); } }
/* 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)); } }
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; } }
#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; }
#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; }
//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)); } }
#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; }
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)
''' 思路:先取矩阵的第一行,接着将剩下作为新矩阵进行一个逆时针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
//此为一个笨办法 //先以(优先级:右下左上)运动; //然后打一个补丁:当运动到一个方向时,优先按照该方向运动 //(笑) 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; } }
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) } }
#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; }
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)); } } }
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); } } } }
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)
旋转矩阵 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)))您的代码已保存