An interesting problem for Spiral matrix!

few days ago . my friend go to have an interview.he saw this meaningful algorithm . like leetcode spiral matrix.

here is my code,in my code,i predefine the matrix is 17*17 🙂

    int arr[17][17];
    int m=17;
    int n=17;
    int i = 0;
    int j = 0;
    int count = 1;
    int the_max = 0;
    int max = m*n;
    // initial to 0
    for (int j = 0; j < n; j++)
    {
        for (int i = 0; i < m; i++)
        {
            arr[i][j] = 0;
        }
    }
    // construct the matrix
    for (; count <= max; )
    {
        i = the_max;
        j = the_max;
        // top row
        for(;i<m-the_max-1;i++){
            arr[i][j] = count++;
        }
        // right column
        for(;j<n-the_max-1;j++){
            arr[i][j] = count++;
        }
        // bottom row
        for(;i>the_max;i--){
            arr[i][j] = count++;
        }
        // left column
        for(;j>the_max;j--){
            arr[i][j] = count++;
        }
        the_max++;
    }

something detail must to be caucion .the odd parameter should have a special process.
since the last row,the first 12 rows cannot print the last row.for example 17*17 , 656,666 wil not show instead of 0.
so i hope i will fix it will the code in the future 🙂

i think this problem also have other more powerful solutions!

Leave a Reply

Your email address will not be published. Required fields are marked *