标签:
3
7 8 1 6 9 2 5 4 3
1 #include <iostream> 2 using namespace std; 3 int a[105][105], visit[105][105],temp = 1, n; 4 5 /*void dfs(int i, int j){ 6 a[i][j] = temp; 7 visit[i][j] = 1; 8 temp++; 9 if(i+1 <= n-1 && visit[i+1][j] == 0) 10 dfs(i+1, j); 11 if(j-1 >= 0 && visit[i][j-1] == 0) 12 dfs(i, j-1); 13 if(i-1 >= 0 && visit[i-1][j] == 0) 14 dfs(i-1, j); 15 if(j+1 <= n-1 && visit[i][j+1] == 0) 16 dfs(i, j+1); 17 } 18 */ 19 20 int main(){ 21 cin >> n; 22 int i = 0, j = n-1; 23 a[0][n-1] = temp; 24 visit[0][n-1] = 1; 25 //dfs(0, n-1); 26 while(temp < n*n){ 27 while(i+1 < n && visit[i+1][j] == 0){ 28 visit[i+1][j] = 1; 29 a[++i][j] = ++temp; 30 } 31 32 while(j-1 >= 0 && visit[i][j-1] == 0){ 33 visit[i][j-1] = 1; 34 a[i][--j] = ++temp; 35 } 36 37 while(i-1 >= 0 && visit[i-1][j] == 0){ 38 visit[i-1][j] = 1; 39 a[--i][j] = ++temp; 40 } 41 42 while(j+1 < n && visit[i][j+1] == 0){ 43 visit[i][j+1] = 1; 44 a[i][++j] = ++temp; 45 } 46 47 } 48 for(int i = 0; i < n; i++){ 49 for(int j = 0; j < n; j++) 50 cout << a[i][j] << " "; 51 cout << endl; 52 } 53 return 0; 54 55 }
标签:
原文地址:http://www.cnblogs.com/qinduanyinghua/p/5576189.html