• [九度][何海涛] 顺时针打印矩阵


    题目描述:

    输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵:

    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.

    输入:

    输入可能包含多个测试样例,对于每个测试案例,

    输入的第一行包括两个整数m和n(1<=m,n<=1000):表示矩阵的维数为m行n列。

    接下来的m行,每行包括n个整数,表示矩阵的元素,其中每个元素a的取值范围为(1<=a<=10000)。

    输出:

    对应每个测试案例,输出一行,

    按照从外向里以顺时针的顺序依次打印出每一个数字,每个数字后面都有一个空格。

    样例输入:
    4 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 

    用类似深度搜索的方法来做,每次朝一个方向走,如果不能再走了顺时针转向。
     1 #include <iostream>
     2 #include <cstdio>
     3 using namespace std;
     4 
     5 int a[1000][1000];
     6 bool canUse[1000][1000];
     7 int step[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
     8 
     9 void print(int x, int y, int direct, int m, int n)
    10 {
    11     canUse[x][y] = false;
    12     printf("%d ", a[x][y]);
    13 
    14     for(int i = 0; i < 4; i++)
    15     {
    16         int j = (direct + i) % 4;
    17         int tx = x + step[j][0];
    18         int ty = y + step[j][1];
    19 
    20         if (0 <= tx && tx < m && 0 <= ty && ty < n && canUse[tx][ty])
    21         {
    22             print(tx, ty, j, m, n); 
    23         }
    24     }
    25 }
    26 
    27 int main()
    28 {
    29     int m, n;
    30     while(scanf("%d%d", &m, &n) != EOF)
    31     {
    32         for(int i = 0; i < m; i++)
    33             for(int j = 0; j < n; j++)
    34             {
    35                 scanf("%d", &a[i][j]);
    36                 canUse[i][j] = true;
    37             }
    38 
    39         print(0, 0, 0, m, n);
    40         printf("\n");
    41     }
    42 }
  • 相关阅读:
    Getting started with the Web ADF
    将搜狗浏览器设置为IIS的默认浏览器
    What is installed with the Web ADF?
    如何修改Flex的默认浏览器
    What is the Web Application Developer Framework
    windows C++获得本地IP地址
    lua table函数库
    【铸铁】C++服务器面试题.doc
    VC2008下提示找不到MSVCP90D.dll的解决办法
    排序
  • 原文地址:https://www.cnblogs.com/chkkch/p/2780599.html
Copyright © 2020-2023  润新知