这是我在Java中顺时针旋转90度方形矩阵的代码。
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
// write your code here
int size = 4;
int[][] matrix = new int[size][size];
for (int i = 0; i < size ; i++) {
for (int j = 0; j < size; j++) {
matrix[i][j] = (i+(2*j));
}
}
trace(matrix, size);
rotate(matrix);
System.out.println("________________________");
trace(matrix, size);
}
public static void rotate(int[][] matrix){
int stop = matrix.length -1;
rotate(matrix, stop, 0);
}
public static void rotate(int[][] matrix, int stop, int start){
if(start - stop == 1) return;
ArrayList<Integer> temp = new ArrayList<>();
//save top row in an array
for (int i = start; i <= stop ; i++) {
temp.add(matrix[start][i]);
}
//left goes to top
for (int i = start; i <= stop ; i++) {
matrix[start][i] = matrix[stop - i][start];
}
//bottom goes to left
for (int i = start; i <= stop ; i++) {
matrix[i][start] = matrix[stop][i];
}
//right goes to bottom
for (int i = start; i <= stop ; i++) {
matrix[stop][stop - i] = matrix[i][stop];
}
//temp array goes to right
for (int i = 0; i < temp.size() ; i++) {
matrix[start + i][stop] = temp.get(i);
}
rotate(matrix, stop-1, start + 1);
}
public static void trace(int[][] matrix, int size){
for (int i = 0; i < size; i++) {
for (int j = 0; j < size ; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}
原始数组和输出如下所示,
0 2 4 6
1 3 5 7
2 4 6 8
3 5 7 9
________________________
3 2 1 0
5 4 3 2
6 2 5 4
3 8 7 6
显然,答案并不完全正确。虽然它几乎就在那里。我对这些错误感到有点迷茫,任何帮助都表示赞赏。
答案 0 :(得分:1)
此代码似乎工作正常。这里的测试用例是一个8x8矩阵,可以根据您的测试用例缩放到4x4。
$qb = $entityManager->createQueryBuilder();
$qb->select('accident.city')->distinct();
$qb->from('VisDatasetBundle:Accident','accident');
$result = $qb->getQuery()->getResult();
$i = 0;
$qb->delete();
while($i < count($result)){
$qb = $entityManager->createQueryBuilder();
$qb->select('count(accident.city)');
$qb->from('VisDatasetBundle:Accident', 'accident');
$qb->where('accident.city = \'' . $result[$i]['city'] . '\'');
$count = $qb->getQuery()->getResult();
$result[$i]['count'] = $count[0]['1'];
$qb->delete();
$i++;
}
return $result;
}