Get the Sum of 对角线 of 螺旋(线) in n X n
Starting with the number 1 and moving to the right in a counter-clockwise
direction a 5 by 5 .
The issue is that the 1 is in the middle.
Normally:
for example :螺旋(线) (3X3)
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
[leetcode]Spiral Matrix II
(2013-03-12 15:14:57)
转载▼
标签:
分类: leetcode
Given an integer n, generate a square matrix filled with elements from 1 to
n2 in spiral order.
For example,
Given n = 3,
You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
class Solution {
public:
vector > generateMatrix(int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector > matrix;
int pi = 0;
int w = n;
int cur = 1;
vector tmp;
for(int i = 0;i < n;i++)
tmp.push_back(0);
for(int i = 0;i < n;i++)
matrix.push_back(tmp);
while(w >= 0)
{
dealWithRect(pi,w,cur,matrix);
w -= 2;
pi += 1;
}
return matrix;
}
void dealWithRect(int pi,int w,int & cur,vector > &matrix)
{
if(w == 0)
return;
if(w == 1)
{
for(int i = 0; i < w;i++)
matrix[pi+i][pi] = cur++;
return;
}
for(int i = 0; i < w;i++)
matrix[pi][pi+i] = cur++;
for(int i = 1; i < w-1;i++)
matrix[pi+i][pi+w-1] = cur++;
for(int i = w-1; i >= 0;i--)
matrix[pi+w-1][pi+i] = cur++;
for(int i = w-2; i >= 1;i--)
matrix[pi+i][pi] = cur++;
}
};
one solution:
using System;
using System.Collections;
using System.Text;
namespace Test
{
class Diagsum
{
static void Main(string[] args)
{
Console.WriteLine(sumdiagprimes(5));
Console.WriteLine(sumdiagprimes(75));
}
public static string sumdiagprimes(int size)
{
long startTime = DateTime.Now.Ticks;
int j = 2;
ArrayList primes = new ArrayList();
while (primes.Count < Math.Pow(size, 2))
{
if (isprime(j))
{
primes.Add(j);
}
j++;
}
primes.Reverse();
int p = size - 1;
int q = 0;
int iter = 0;
ArrayList result = new ArrayList();
while(q<=primes.Count-1 && p>0)
{
for(int i=1; i<=5; i++)
{
iter++;
if (q <= primes.Count - 1)
{
//Console.WriteLine("p="+p+" q="+q);
if (result.Count==0 || (result[result.Count - 1] !=
primes[q]))
{
result.Add(primes[q]);
}
q = q + p;
}
else
{
break;
}
}
//Console.WriteLine("old q=" + q);
q = q - p;
//Console.WriteLine("new q="+q);
p=p-2;
}
if((size % 2) != 0)
{
result.Add(result[result.Count-1]);
}
Int64 resultsum = 0;
for (int i = 0; i <= result.Count-1; i++)
{
resultsum = resultsum + Convert.ToInt64(result[i]);
}
//PrintValues(result);
long endTime = DateTime.Now.Ticks;
TimeSpan timeTaken = new TimeSpan(endTime - startTime);
return "size: "+size+"\r\niter: "+iter+"\r\ntime: "+timeTaken.
ToString()+"\r\n sum: "+resultsum+"\r\n\r\n";
}
public static bool isprime(int number)
{
int i = 0;
if (number < 2)
{
return false;
}
else
{
for (i = 2; i <= (number / 2); i++)
{
if (number % i == 0)
{
return false;
}
}
return true;
}
}
public static void PrintValues(IEnumerable myList)
{
foreach (Object obj in myList)
Console.Write("{0},", obj);
Console.WriteLine();
}
}
}