算法:给定一个包含 m x n 个元素的矩阵(即:m行n列的矩阵),按照螺旋顺序打印出矩阵中的所有元素。
示例:给定如下矩阵
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
则最终打印出的顺序为:1, 2, 3, 6, 9, 8, 7, 4, 5
1 --[[ 2 给定一个包含 m x n 个元素的矩阵(即:m行n列的矩阵),按照螺旋顺序打印出矩阵中的所有元素。 3 示例:给定如下矩阵 4 [1, 2, 3] 5 [4, 5, 6] 6 [7, 8, 9] 7 则最终打印出的顺序为:1, 2, 3, 6, 9, 8, 7, 4, 5 8 --]] 9 10 function traversal_print(data) 11 12 local row_max = #data; -- max row 13 local col_max = #(data[1]); -- max column 14 15 local row = 1; 16 local col = 1; 17 local row_end = row_max; 18 local col_end = col_max; 19 20 local begin_time= os.clock(); 21 22 local temp = 0; 23 while (row <= row_end) and (col <= col_end) do 24 for temp = col, col_end do 25 print(data[row][temp]); 26 end 27 28 if row_end > row then 29 for temp = row + 1, row_end do 30 print(data[temp][col_end]); 31 end 32 end 33 34 if (col_end > col) and (row_end > row) then 35 for temp = col_end - 1, col, -1 do 36 print(data[row_end][temp]); 37 end 38 end 39 40 if (row_end - 1 > row) and (col_end > col) then 41 for temp = row_end - 1, row + 1, -1 do 42 print(data[temp][col]); 43 end 44 end 45 46 if (row_end - row >= 0) and (col_end - col >= 0) then 47 row = row + 1; 48 row_end = row_end - 1; 49 col = col + 1; 50 col_end = col_end - 1; 51 end 52 end 53 54 local elaplsed_time = os.clock() - begin_time; 55 print("-- total elasped: "..elaplsed_time.." --"); 56 end 57 58 --[[--]] 59 local _data = { 60 {1, 2, 3}, 61 {4, 5, 6}, 62 {7, 8, 9} 63 }; 64 65 66 --[[ 67 local _data = { 68 {1, 2, 3} 69 }; 70 --]] 71 72 --[[ 73 local _data = { 74 {1}, 75 {4}, 76 {7} 77 }; 78 --]] 79 80 traversal_print(_data);
1 void tt5() { 2 const int ROW_MAX = 3; 3 const int COL_MAX = 3; 4 int data[ROW_MAX][ROW_MAX] = { 5 { 1, 2, 3 }, 6 { 4, 5, 6 }, 7 { 7, 8, 9 } 8 }; 9 int nRow = 0; 10 int nCol = 0; 11 int nRowEnd = ROW_MAX - 1; 12 int nColEnd = COL_MAX - 1; 13 14 const auto begin_time = clock(); 15 int nTemp = 0; 16 while (nRow <= nRowEnd && nCol <= nColEnd) { 17 for (nTemp = nCol; nTemp <= nColEnd; ++nTemp) { 18 std::cout << data[nRow][nTemp] << std::endl; 19 } 20 21 if (nRowEnd > nRow) { 22 for (nTemp = nRow + 1; nTemp <= nRowEnd; ++nTemp) { 23 std::cout << data[nTemp][nColEnd] << std::endl; 24 } 25 } 26 27 if (nColEnd > nCol && nRowEnd > nRow) { 28 for (nTemp = nColEnd - 1; nTemp >= nCol; --nTemp) { 29 std::cout << data[nRowEnd][nTemp] << std::endl; 30 } 31 } 32 33 if (nRowEnd - 1 > nRow && nColEnd > nCol) { 34 for (nTemp = nRowEnd - 1; nTemp >= nRow + 1; --nTemp) { 35 std::cout << data[nTemp][nCol] << std::endl; 36 } 37 } 38 39 if (nRowEnd >= nRow && nColEnd >= nCol) { 40 ++nRow; 41 --nRowEnd; 42 ++nCol; 43 --nColEnd; 44 } 45 } 46 const auto elapsed_time = clock() - begin_time; 47 std::cout << "-- total elapsed: " << elapsed_time << " --" << std::endl; 48 }
经多次测试,相对来说,还是c++效率会优于Lua。