Logic needed with explanation.

Hi I need to come up with a solution for the following problem. Tell me how to code in C?

Input:

1 2 3 4

Output:

1 2 3 4 
4 1 2 1
3 4 3 2
2 1 4 3

what if my answer is

#include<stdio>
int main(){

printf("1 2 3 4\n");
printf(" 4 1 2 1\n");
printf("3 4 3 2\n");
printf("2 1 4 3\n");
return 0;
}

Bad right , the same is your question :stuck_out_tongue:

6 Likes

Have a look at below codes

  1. C++ code by mohit_at_codepad - 58 lines - codepad
  2. C++ code by mohit_at_codepad - 57 lines - codepad

In main use w = 4 and h = 4.
Moreover in cout (while printing), numbers larger than 4 to smaller numbers.

ex: C++ code by mohit_at_codepad - 55 lines - codepad

1 Like

Google search spiral matrix implementation

1 Like

Having a problem statement would make things easier. It looks like a permutation of the input repeated 4 times but what exactly are you trying to achieve? You have to help us help you.

1 Like

i think he wants to print it in spiral form!!!

if this is ne kind of homework…then pls do it yourself…try it…if u get stuck somewhere then ask…and provide your code…it is easy…just give it a shot!!!

nice gesture :slight_smile: Will implement it now :slight_smile: Thanx for the explanation

This answer just made my day :smiley:

3 Likes

:stuck_out_tongue: :smiley: hahaha

:smiley: lol good one

Thanks a lot… I find it difficult to understand your logic… I must spend some time with the code to crack it…

You can initialize the matrix with all -1. (-1 means not visited)

  1. Start with (x = 0, y = 0), written = 0

  2. while x < width && arr[x][y] == -1, arr[x++][y] = next number, ++written.

  3. –x, ++y

  4. while y < height && arr[x][y] == -1, arr[x][y++] = next number, ++written.

  5. –x, --y

  6. while x >= 0 && arr[x][y] == -1, arr[x–][y] = next number, ++written.

  7. ++x, --y

  8. while y >= 0 && arr[x][y] == -1, arr[x][y–] = next number, ++written

  9. ++x, ++y

  10. if written != width * height, go to step 2
    Try to implement this, if you find anything difficult do post it.