Created
April 15, 2016 04:43
-
-
Save jianminchen/12b58729c59e44a0d71d9f9c47bc937c to your computer and use it in GitHub Desktop.
matrix rotation - with bugs to fix
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace RotateArray2 | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
string s1 = Console.ReadLine(); | |
string[] sA = s1.Split(' '); | |
int row = Convert.ToInt16(sA[0].Trim()); | |
int col = Convert.ToInt16(sA[1].Trim()); | |
int T = Convert.ToInt16(sA[2].Trim()); | |
int[][] arr = new int[row][]; | |
for (int i = 0; i < row; i++) | |
arr[i] = new int[col]; | |
for (int i = 0; i < row; i++) | |
{ | |
string s = Console.ReadLine(); | |
string[] aA = s.Split(' '); | |
if (aA.Length != col) | |
return; | |
for (int j = 0; j < col; j++) | |
arr[i][j] = Convert.ToInt16(aA[j].Trim()); | |
} | |
for (int i = 0; i < T; i++) | |
rotateArrayOneStepAntiClockwise(arr); | |
for (int i = 0; i < row; i++) | |
{ | |
string s = ""; | |
for (int j = 0; j < col; j++) | |
s += arr[i][j].ToString() + " "; | |
Console.WriteLine(s); | |
} | |
} | |
/* | |
* Do it in place | |
*/ | |
public static bool rotateArrayOneStepAntiClockwise(int[][] arr) | |
{ | |
if (arr == null) return false; | |
int row = arr.Length; // row | |
int col = arr[0].Length; // column | |
int startR = 0; | |
int startC = 0; | |
while (startR < row/2 && startC < col/2) | |
{ | |
int firstRow = startR; | |
int lastRow = row - startR - 1; | |
int firstCol = startC; | |
int lastCol = col - startC - 1; | |
int tmpValue = arr[startR][startC]; | |
// for up row Direction: L -> R | |
for (int i = firstCol + 1; i <= lastCol; i++ ) | |
arr[firstRow][i - 1] = arr[firstRow][i]; | |
// for right column Direction: top -> down | |
for (int i = firstRow + 1; i <= lastRow; i++) | |
arr[i - 1][lastCol] = arr[i][lastCol]; | |
// for down row - Direction: R -> L | |
for (int i = lastCol; i > firstCol ; i-- ) | |
arr[lastRow][i] = arr[lastRow][i - 1]; | |
// for left column - Direction: Down -> up first 2 rows - no touch | |
for (int i = lastRow; i >= firstRow + 2 ; i--) // | |
arr[i][firstCol] = arr[i - 1][firstCol]; | |
arr[firstRow + 1][firstCol] = tmpValue; | |
startR++; | |
startC++; | |
} | |
return true; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment