Created
April 12, 2016 18:54
-
-
Save jianminchen/6eb6244fbb1912e3a06e672f604f87e0 to your computer and use it in GitHub Desktop.
Rotate Array - fix bugs - work on base cases, two of them, 2x2, 3x3
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) | |
{ | |
int k = Convert.ToInt16(Console.ReadLine()); | |
int[][] arr = new int[k][]; | |
for (int i = 0; i < k; i++) | |
arr[i] = new int[k]; | |
for (int i = 0; i < k; i++) | |
{ | |
string s = Console.ReadLine(); | |
string[] aA = s.Split(' '); | |
if (aA.Length != k) | |
return; | |
for (int j = 0; j < k; j++) | |
arr[i][j] = Convert.ToInt16(aA[j].Trim()); | |
} | |
if (rotateArray(arr, k)) | |
{ | |
for (int i = 0; i < k; i++) | |
{ | |
string s = ""; | |
for (int j = 0; j < k; j++) | |
s += arr[i][j].ToString() + " "; | |
Console.WriteLine(s); | |
} | |
} | |
else | |
Console.WriteLine("ERROR"); | |
} | |
/* | |
* Do it in place | |
*/ | |
public static bool rotateArray(int[][] arr, int k) | |
{ | |
if (arr == null) return false; | |
int n = arr.Length; // row | |
int m = arr[0].Length; // column | |
if (n != m) return false; | |
if (n != k) return false; | |
int start = 0; | |
int end = k - 1; | |
while (start <= end && start < k / 2) | |
{ | |
// for left column | |
swap(arr, start, start, start, start + 1, k); | |
for (int i = start + 1; i <= end; i++) | |
{ | |
swap(arr, i, start, i - 1, start, k); | |
} | |
// for down row - swap | |
for (int i = start; i < end; i++) | |
{ | |
swap(arr, end, i, end, i + 1, k); | |
} | |
// for right column | |
// for (int i = end; i > start; i--) // bug 001 if there are only two rows, exception | |
for (int i = end; i > start && (end-start) > 1; i--) // bug001 fix - do not swap if there are two rows | |
{ | |
swap(arr, i, end, i - 1, end, k); | |
} | |
// for up row | |
for (int i = end; i > start + 2; i--) | |
{ | |
swap(arr, start, i, start, i - 1, k); | |
} | |
start++; | |
end--; | |
} | |
return true; | |
} | |
private static void swap(int[][] arr, int x1, int y1, int x2, int y2, int maxRow) | |
{ | |
if (!(x1 < maxRow && y1 < maxRow && x2 < maxRow && y2 < maxRow)) | |
return; | |
if (!(x1 >= 0 && y1 >= 0 && x2 >= 0 && y2 >= 0)) | |
return; | |
int tmp = arr[x1][y1]; | |
arr[x1][y1] = arr[x2][y2]; | |
arr[x2][y2] = tmp; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment