本文主要是介绍分治算法之数字旋转方阵问题,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一、矩阵形式如下:
1 16 15 14 13
2 17 24 23 12
3 18 25 22 11
4 19 20 21 10
5 6 7 8 9
二、利用分治算法的思想,先生成矩阵的如下区域:
区域A:
1 | ||||
2 | ||||
3 | ||||
4 | ||||
5 | 6 | 7 | 8 |
区域C:
12 | ||||
11 | ||||
10 | ||||
9 |
区域D:
16 | 15 | 14 | 13 | |
public class RotateMatrix {public static int N = 5;int [][] result = new int[N][N];public static void main(String[] args) {RotateMatrix rm = new RotateMatrix();rm.generateRotate(1, 0, N);rm.printResult();}//生成旋转矩阵public void generateRotate(int number, int begin, int size){if(size == 1){result[begin][begin] = number;return;}if(size == 0){return;}//生成区域Aint i = begin;int j = begin;for(int k = 0; k < size - 1; k++){result[i][j] = number;number++;i++;}//生成区域Bfor(int k = 0; k < size - 1; k++){result[i][j] = number;number++;j++;}//生成区域Cfor(int k = 0; k < size - 1; k++){result[i][j] = number;number++;i--;}//生成区域Dfor(int k = 0; k < size - 1; k++){result[i][j] = number;number++;j--;}//递归调用generateRotate(number, begin + 1, size - 2);}//打印结果public void printResult(){for(int i = 0; i < N; i++){for(int j = 0; j < N; j++){System.out.print(result[i][j] + " ");if(j == N - 1){System.out.println();}}}}
}
四、运行结果如下:
1 16 15 14 13
2 17 24 23 12
3 18 25 22 11
4 19 20 21 10
5 6 7 8 9
这篇关于分治算法之数字旋转方阵问题的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!