Skip to content

Instantly share code, notes, and snippets.

@c02y
Created January 15, 2020 08:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save c02y/ca086e400f1b1d375f534f07bf45a66d to your computer and use it in GitHub Desktop.
Save c02y/ca086e400f1b1d375f534f07bf45a66d to your computer and use it in GitHub Desktop.
29. 顺时针打印矩阵
#!/usr/bin/env python3
# https://cyc2018.github.io/CS-Notes/#/notes/29.%20%E9%A1%BA%E6%97%B6%E9%92%88%E6%89%93%E5%8D%B0%E7%9F%A9%E9%98%B5
class Solution:
def printMatrix(self, matrix):
res = []
while matrix:
res += matrix.pop(0)
if matrix and matrix[0]:
for row in matrix:
res.append(row.pop())
if matrix:
res += matrix.pop()[::-1]
if matrix and matrix[0]:
for row in matrix[::-1]:
res.append(row.pop(0))
return res
if __name__ == '__main__':
matrix = [[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]]
print(Solution().printMatrix(matrix))
@c02y
Copy link
Author

c02y commented Jan 15, 2020

CPP version:

#include <iostream>
#include <vector>

using namespace std;

class Solution {
public:
	vector<int> printMatrix(vector<vector<int>> matrix) {
		int row=matrix.size();
		int col=matrix[0].size();
		vector<int> result;
		if(row==0||col==0)
			return result;
		int left=0,right=col-1,top=0,btm=row-1;
		while(left<=right&&top<=btm)
		{
			for(int i=left;i<=right;i++)
				result.push_back(matrix[top][i]);
			if(top<btm)
				for(int i=top+1;i<=btm;i++)
					result.push_back(matrix[i][right]);
			if(top<btm&&left<right)
				for(int i=right-1;i>=left;i--)
					result.push_back(matrix[btm][i]);
			if(top+1<btm&&left<right)
				for(int i=btm-1;i>=top+1;i--)
					result.push_back(matrix[i][left]);
			left++;right--;top++;btm--;
		}
		return result;
	}
};

int main(void)
{
	vector<vector<int>> matrix{ {1, 2, 3, 4},
								{5, 6, 7, 8},
								{9, 10, 11, 12},
								{13, 14, 15, 16} };

	vector<int > vect = Solution().printMatrix(matrix);
	for (int i = 0; i < vect.size(); i++)
		cout << vect[i] << ' ';

	return 0;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment