当只有零点的带外的行和列【难度:2级】:
答案1:
public class Kata
{
public static int[][] Crop(int[][] a)
{
int firstRow = 0;
int lastRow = 0;
int firstCol = 1000000;
int lastCol = 0;
bool hasFirst = false;
for (int i = 0; i < a.Length; i++)
{
for (int j = 0; j < a[i].Length; j++)
{
if (a[i][j] > 0 && !hasFirst)
{
hasFirst = true;
firstRow = i;
}
if (a[i][j] > 0)
{
lastRow = i;
firstCol = System.Math.Min(j, firstCol);
lastCol = System.Math.Max(j, lastCol);
}
}
}
int col = 0;
int row = 0;
if (firstCol == 1000000) return new int[0][];
int[][] ans = new int[lastRow - firstRow + 1][];
for (int i = 0; i < ans.Length; i++) ans[i] = new int[lastCol - firstCol + 1];
for (int i = firstRow; i <= lastRow; i++)
{
for (int j = firstCol; j <= lastCol; j++) ans[row][col++] = a[i][j];
col = 0;
row++;
}
return ans;
}
}
答案2:
using System.Linq;
public class Kata
{
public static int[][] Crop(int[][] matrix)
{
var x1 = 0;
var x2 = matrix[0].Length-1;
var y1 = 0;
var y2 = matrix.Length-1;
var y1reached = false;
var y2reached = false;
var x1reached = false;
var x2reached = false;
while((y1 < (y2+1)) && ((!y1reached) || (!y2reached)))
{
if(matrix[y1].Count(o => o != 0) == 0)
{
y1++;
}
else
{
y1reached = true;
}
if(matrix[y2].Count(o => o != 0) == 0)
{
y2--;
}
else
{
y2reached = true;
}
}
while((x1 < (x2+1)) && ((!x1reached) || (!x2reached)))
{
var x1IsNotZero = false;
var x2IsNotZero = false;
for(var i = y1; i <= y2; i++)
{
if(matrix[i][x1] != 0)
{
x1IsNotZero = true;
}
if(matrix[i][x2] != 0)
{
x2IsNotZero = true;
}
}
if(x1IsNotZero == false)
{
x1++;
}
else
{
x1reached = true;
}
if(x2IsNotZero == false)
{
x2--;
}
else
{
x2reached = true;
}
}
if(y1 > y2)
{
return new int[0][];
}
var newMatrix = new int[y2-y1 + 1][];
for(var i = 0; i < y2-y1 +1; i++)
{
var newLine = new int[x2 - x1 + 1];
for(var j = 0; j < x2 - x1 + 1; j++)
{
newLine[j] = matrix[y1+i][x1 + j];
}
newMatrix[i] = newLine;
}
return newMatrix;
}
}