Spiral Matrix

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

For example,
Given the following matrix:

[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]

You should return [1,2,3,6,9,8,7,4,5].

_________________________________________________________________________________________________________

void visitAll(vector<int> &result, vector<vector<int>>& matrix, int curLayer)
{
int row = matrix.size();
int col = matrix[0].size();

//visit up
for(int i=curLayer;i<col-curLayer-1;i++)
result.push_back(matrix[curLayer][i]);

//visit right
for(int i=curLayer;i<row-curLayer-1;i++)
result.push_back(matrix[i][col-curLayer-1]);

//visit down – visited from end to start
for(int i=col-curLayer-1;i>=curLayer+1;i–)
result.push_back(matrix[row-curLayer-1][i]);

//visit left – visit from bottom to top
for(int i=row-curLayer-1;i>=curLayer+1;i–)
result.push_back(matrix[i][curLayer]);
}

vector<int> spiralOrder(vector<vector<int> > &matrix) {
// Start typing your C/C++ solution below
// DO NOT write int main() function

vector<int> result;

if(matrix.empty())
return result;

int row = matrix.size();
int col = matrix[0].size();
int layer;

if(row==1)
{
for(int i=0;i<col;i++)
result.push_back(matrix[row-1][i]);

return result;
}
else if(col==1)
{
for(int i=0;i<row;i++)
result.push_back(matrix[i][col-1]);

return result;
}
else if(row>=col)
layer = col/2;
else
layer = row/2;

for(int i=0;i<layer;i++)
visitAll(result, matrix, i);

if(row%2!=0)
{
for(int i=layer;i<col-layer;i++)
result.push_back(matrix[layer][i]);
}
else if(col%2!=0)
{
for(int i=layer;i<row-layer;i++)
result.push_back(matrix[i][layer]);
}

return result;
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s