Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created February 10, 2018 00:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/7895c41ffe2a946920310d53af94c361 to your computer and use it in GitHub Desktop.
Save jianminchen/7895c41ffe2a946920310d53af94c361 to your computer and use it in GitHub Desktop.
Leetcode 54 - spiral matrix - recursive solution
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sprila_matrix_recursive
{
/// <summary>
/// Leetcode 54: Spiral matrix
///
/// </summary>
class Program
{
static void Main(string[] args)
{
RunTestcase();
}
public static void RunTestcase()
{
var spiral = MatrixSpiralPrint(new int[][] { new int[]{ 1, 2, 3 }, new int[]{ 8, 9, 4 }, new int[]{ 7, 6, 5 } });
Debug.Assert(String.Join("", spiral).CompareTo("123456789") == 0);
}
public static IList<int> MatrixSpiralPrint(int[][] matrix)
{
var result = new List<int>();
if (matrix == null || matrix.Length == 0 || matrix[0].Length == 0)
{
return result;
}
helper(matrix, result, 0, 0, matrix.Length - 1, matrix[0].Length - 1);
return result;
}
/// <summary>
/// recursive function -
/// check base cases:
/// out of array range
/// one element
/// one row
/// one column
///
/// </summary>
/// <param name="matrix"></param>
/// <param name="result"></param>
/// <param name="rowStart"></param>
/// <param name="colStart"></param>
/// <param name="rowEnd"></param>
/// <param name="colEnd"></param>
private static void helper(int[][] matrix, IList<int> result, int rowStart, int colStart, int rowEnd, int colEnd)
{
// stop situation
if (rowStart > rowEnd || colStart > colEnd)
{
return;
}
var current = matrix[rowStart][colStart];
// only one element in the sub matrix
if (rowStart == rowEnd && colStart == colEnd)
{
result.Add(current);
return;
}
// only one row in the sub matrix
if (rowStart == rowEnd)
{
// add this row
for (int col = colStart; col <= colEnd; col++)
{
result.Add(matrix[rowStart][col]);
}
return;
}
// only one column in the sub matrix
if (colStart == colEnd)
{
// add this column
for (int row = rowStart; row <= rowEnd; row++)
{
result.Add(matrix[row][colStart]);
}
return;
}
// other cases, recursive adding all
// add first row
for (int col = colStart; col < colEnd; col++)
{
result.Add(matrix[rowStart][col]);
}
// add last column
for (int row = rowStart; row < rowEnd; row++)
{
result.Add(matrix[row][colEnd]);
}
// add last row
for (int col = colEnd; col > colStart; col--)
{
result.Add(matrix[rowEnd][col]);
}
// add first column
for (int row = rowEnd; row > rowStart; row--)
{
result.Add(matrix[row][colStart]);
}
// recursive adding sub matrix
helper(matrix, result, rowStart + 1, colStart + 1, rowEnd - 1, colEnd - 1);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment