标签:
题目要求:
思路:
我的最初思路:
将矩阵的四个边作为边界,一个循环执行四次九十度转弯,用swich、case实现,当四个边界指向一个位置结束循环,但是在拐点的处理上比较麻烦。
资料参考的思路:
写一个函数,输出二维数组一圈的元素。
循环执行上个函数,也就是输出每个圈的元素。
这个思路更好理解一些。
代码:
#include<iostream>
using namespace std;
void printEdge(int * m, int tR, int tC, int dR, int dC,int row,int col) {
if (tR == dR) {
// 子矩阵只有一行时
for (int i = tC; i <= dC; i++) {
cout<<*(m+i)<<endl;
}
}
else if (tC == dC) {
// 子矩阵只有一列时
for (int i = tR; i <= dR; i++) {
cout<<*(m+col*i+tC)<<endl;
}
}
else { // 一般情况
int curC = tC;
int curR = tR;
while (curC != dC) {
cout<<*(m+tR*col+curC)<<endl;
curC++;
}
while (curR != dR) {
cout<<*(m+curR*col+dC)<<endl;
curR++;
}
while (curC != tC) {
cout<<*(m+col*dR+curC)<<endl;
curC--;
}
while (curR != tR) {
cout<<*(m+col*curR+tC)<<endl;
curR--;
}
}
}
void spiralOrder(int* matrix,int row,int col)
{
int tR = 0;
int tC = 0;
int dR = row -1;
int dC = col -1;
while(tR<=dR&&tC<=dC)
{
printEdge(matrix, tR++, tC++, dR--, dC--,col,row);
}
}
int main()
{
int a[][4] = {1,2,3,6};
spiralOrder((int*) a,1,4);
int b[][4] = {
{1},
{2},
{3},
{16}
};
spiralOrder((int*) b,4,1);
cout<<"/////////////////////////"<<endl;
int c[][4] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
spiralOrder((int*) c,4,4);
/*
int N = 4;
int sum = 0;
int flag = 0;
int right = N-1;
int left = 0;
int up = 1;
int down = N-1;
int x = 0;
int y = -1;
while(sum<N*N)
{
switch(flag)
{
case 0:
y = y+1;
while(y<=right)
{
cout<<a[x][y]<<endl;
sum = sum +1;
y++;
}
y = right;
right = right-1;
flag = 1;
break;
case 1:
x = x+1;
while(x<=down)
{
cout<<a[x][y]<<endl;
sum = sum +1;
x++;
}
x = down;
down = down-1;
flag = 2;
break;
case 2:
y = y-1;
while(y>=left)
{
cout<<a[x][y]<<endl;
y = y-1;
sum++;
}
y = left;
left = left +1;
flag = 3;
break;
case 3:
x = x-1;
while(x>=up)
{
cout<<a[x][y]<<endl;
x = x-1;
sum++;
}
x = up;
up = up+1;
flag = 0;
break;
default:
break;
}
}*/
return 0;
}
java:
package chapter_8_arrayandmatrix;
public class Problem_01_PrintMatrixSpiralOrder {
public static void spiralOrderPrint(int[][] matrix) {
int tR = 0;
int tC = 0;
int dR = matrix.length - 1;
int dC = matrix[0].length - 1;
while (tR <= dR && tC <= dC) {
printEdge(matrix, tR++, tC++, dR--, dC--);
}
}
public static void printEdge(int[][] m, int tR, int tC, int dR, int dC) {
if (tR == dR) { // 子矩阵只有一行时
for (int i = tC; i <= dC; i++) {
System.out.print(m[tR][i] + " ");
}
} else if (tC == dC) { // 子矩阵只有一列时
for (int i = tR; i <= dR; i++) {
System.out.print(m[i][tC] + " ");
}
} else { // 一般情况
int curC = tC;
int curR = tR;
while (curC != dC) {
System.out.print(m[tR][curC] + " ");
curC++;
}
while (curR != dR) {
System.out.print(m[curR][dC] + " ");
curR++;
}
while (curC != tC) {
System.out.print(m[dR][curC] + " ");
curC--;
}
while (curR != tR) {
System.out.print(m[curR][tC] + " ");
curR--;
}
}
}
public static void main(String[] args) {
int[][] matrix = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 },
{ 13, 14, 15, 16 } };
spiralOrderPrint(matrix);
}
}
标签:
原文地址:http://blog.csdn.net/songzige/article/details/51347886