劍指offer-順時針打印矩陣python

輸入一個矩陣,按照從外向裏以順時針的順序依次打印出每一個數字,例如,如果輸入如下4 X 4矩陣: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 則依次打印出數字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.

python:

class Solution:
    # matrix類型爲二維列表,需要返回列表
    def printMatrix(self, matrix):
        # write code here
        if matrix==[[]]:
        	return
        res=[]
        start=0
        rows=len(matrix)
        columns=len(matrix[0])
        while(rows>start*2 and columns>start*2):
        	res += self.PrintMatrixInCircle(matrix,rows,columns,start)
        	start+=1
        return res

    def PrintMatrixInCircle(self,matrix,rows,columns,start):
    	endX=columns-start-1
    	endY=rows-start-1
    	res=[]
    	#從左到右打印一行
    	for i in range(start,endX+1):
    		res.append(matrix[start][i])
    	#從上到下打印一列
    	if start<endY:
    		for i in range(start+1,endY+1):
    			res.append(matrix[i][endX])
    	#從右到左打印一行
    	if start<endX and start<endY:
    		for i in range(endX-1,start-1,-1):
    			res.append(matrix[endY][i])
    	#從下到上打印一列
    	if start<endX and start<endY-1:
    		for i in range(endY-1,start,-1):
    			res.append(matrix[i][start])
    	return res

c++

void PrintMatrixClockwisely(int** numbers, int columns, int rows)
{
	if (numbers == nullptr || columns <= 0 || rows <= 0)
		return;
	int start = 0;
	while (columns > start * 2 && rows > start * 2)
	{
		PrintMatrixInCircle(numbers, columns, rows, start);
		++start;
	}	
}

void PrintMatrixInCircle(int** numbers, int columns, int rows, int start)
{
	int endX = columns - start - 1;
	int endY = rows - start - 1;

	//從左到右打印第一行
	for (int i = 0; i <= endX; i++)
	{
		int number = numbers[start][i];
		print(number);
	}

	//從上到下打印一列
	if (start < endY)
	{
		for (int i = start + 1; i <= endY; i++)
		{
			int number = numbers[i][endX];
			print(number);
		}
	}

	//從右到左打印一行
	if (start < endX && start < endY)
	{
		for (int i = endX-1; i >= start; i--)
		{
			int number = numbers[endY][i];
			print(number);
		}
	}

	//從下到上打印一列
	if (start < endX && start < endY - 1)
	{
		for (int i = endY - 1, i > start; i--)
		{
			int number = numbers[i][start];
			print(number);
		}
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章