Serpentine matrix (round and round) 1412

Subject description:

N rows and n columns of a matrix by a method of generating a serpentine:

Starting from the top left corner (row 1, column 1) matrix, initially moves to the right; If the front grid is never passed, then move on, or turn right; the above-described operation is repeated until all the lattice through the matrix. The sequence passes, sequentially filled in the grid 1, 2, 3, ..., n ^ 2, they constitute a serpentine matrix, where 1 <= n <= 30000. Now given the number of matrix size n and i and j, you find the matrix in row i and column j is the number?

1 2 3 4

12 13 14 5

11 16 15 6

10 9 8 7

Enter a description:

Input common line, comprising three integers n, i, j, between each two integers separated by a space, the size of the matrix, respectively, be seeking the row number and column number is located.

Output Description:

The output common line, contains an integer that represents the number of i-th row j-th column of the respective matrix.

Sample input:

4 2 3

Sample output:

14

thought:

#include <iostream>
using namespace std;
int main() {
    int n,p,q;
    while(cin>>n>>p>>q){
	    int a=n,b=n,c=1,d=1,xx=1,yy=1,sum=1;
	    if(n%2==1&&(n+1)/2==p&&(n+1)/2==q)
	        sum=n*n;
	    else {
	        while(true) {
	            if(xx==p&&q>=yy&&q<a) {
	                sum+=(q-yy);
	                break;
	            } else {
	                sum+=(a-yy);
	                yy=a;
	            }
	            a--;
	            if(yy==q&&p>=xx&&p<b) {
	                sum+=(p-xx);
	                break;
	            } else {
	                sum+=(b-xx);
	                xx=b;
	            }
	            b--;
	            if(xx==p&&q<=yy&&q>c) {
	                sum+=(yy-q);
	                break;
	            } else {
	                sum+=(yy-c);
	                yy=c;
	            }
	            c++;
	            if(yy==q&&p<=xx&&p>d) {
	                sum+=(xx-p);
	                break;
	            } else {
	                sum+=(xx-d);
	                xx=d+1;
	                yy=c;
	            }
	            d++;
	        }
	    }
	    cout<<sum<<endl;
	}
    return 0;
}

  

Upgraded version

 1 #include <iostream>
 2 using namespace std;
 3 int main(){
 4     long n,i,j,p;
 5     cin>>n>>i>>j; 
 6     long m=0,k,s,num=1;
 7     long c[n][n];
 8     p=n/2;
 9     s=n-1;
10     while(s>m){
11         for(k=m;k<s;k++){
12             c[m][k]=num;
13             num++;
14         }
15         for(k=m;k<s;k++){
16             c[k][s]=num;
17             num++;
18         }
19         for(k=s;k>m;k--){
20             c[s][k]=num;
21             num++;
22         }
23         for(k=s;k>m;k--){
24             c[k][m]=num;
25             num++;
26         }
27         s--;
28         m++;
29     }
30     if(n%2!=0){
31         c[p][p]=n*n;
32     }
33     cout<<c[i-1][j-1];
34     return 0;
35 }

 

Guess you like

Origin www.cnblogs.com/zq-dmhy/p/11070185.html