1. 程式人生 > >劍指offer(面試題29):順時針列印矩陣

劍指offer(面試題29):順時針列印矩陣

/*
* 順時針列印矩陣 
* 注意矩陣的維度 
*/
#include<iostream>
using namespace std;

//只要當前的起始行號小於終止行號或者起始列號小於終止列號,就可以繼續順時針列印
// 但是隨著順勢怎列印,剩下的未列印的子矩陣可能收縮成一行或一列,此時需要判斷跳出迴圈
void printMatrixClockwisely(int **matrix, int m, int n) {
    int m_s = 0, m_e = m - 1;
    int n_s = 0, n_e = n - 1;

    while(m_s < m_e || n_s < n_e) {
        for
(int i = n_s; i <= n_e; ++i) cout << matrix[m_s][i] << " "; if(m_s == m_e) break; m_s ++; for(int i = m_s; i <= m_e; ++i) cout << matrix[i][n_e] << " "; if(n_e == n_s) break; n_e --; for
(int i = n_e; i >= n_s; --i) cout << matrix[m_e][i] << " "; if(m_e == m_s) break; m_e --; for(int i = m_e; i >= m_s; --i) cout << matrix[i][n_s] << " "; if(n_s == n_e) break; n_s ++; } } int
main() { int m = 3, n = 4; int **p = new int*[m]; for(int i = 0; i < m; ++i) { p[i] = new int[n]; for(int j = 0; j < n; ++j) { p[i][j] = i*(m+1)+j; cout << p[i][j] << " "; } } cout << endl; // cout << p[0][1]; cout << "(3 * 4)" << endl; printMatrixClockwisely(p,m,n); cout << endl << endl; for(int i = 0; i < m; i++) delete []p[i]; m = 1; n = 4; p = new int*[m]; for(int i = 0; i < m; ++i) { p[i] = new int[n]; for(int j = 0; j < n; ++j) { p[i][j] = i*(m+1)+j; cout << p[i][j] << " "; } } cout << endl; cout << "(1 * 4)" << endl; printMatrixClockwisely(p,m,n); cout << endl << endl; for(int i = 0; i < m; i++) delete []p[i]; m = 2; n = 4; p = new int*[m]; for(int i = 0; i < m; ++i) { p[i] = new int[n]; for(int j = 0; j < n; ++j) { p[i][j] = i*(m+1)+j; cout << p[i][j] << " "; } } cout << endl; cout << "(2 * 4)" << endl; printMatrixClockwisely(p,m,n); cout << endl << endl; for(int i = 0; i < m; i++) delete []p[i]; m = 4; n = 1; p = new int*[m]; for(int i = 0; i < m; ++i) { p[i] = new int[n]; for(int j = 0; j < n; ++j) { p[i][j] = i*(m+1)+j; cout << p[i][j] << " "; } } cout << endl; cout << "(4 * 1)" << endl; printMatrixClockwisely(p,m,n); cout << endl << endl; for(int i = 0; i < m; i++) delete []p[i]; m = 4; n = 4; p = new int*[m]; for(int i = 0; i < m; ++i) { p[i] = new int[n]; for(int j = 0; j < n; ++j) { p[i][j] = i*(m+1)+j; cout << p[i][j] << " "; } } cout << endl; cout << "(4 * 4)" << endl; printMatrixClockwisely(p,m,n); cout << endl << endl; }