当前位置: 代码迷 >> 综合 >> 算法竞赛入门经典的java实现之蛇形填数-Demo18.java
  详细解决方案

算法竞赛入门经典的java实现之蛇形填数-Demo18.java

热度:84   发布时间:2023-10-27 06:10:48.0

在n*n的方阵里填入,1,2,3,4,~,n*n,要求填成蛇形。例如n=4时,方阵为:

10    11    12    1

  9    16    13    2

  8    15    14    3

  7      6      5    4

上面的方阵中,多余的空格只是为了便于观察,不必严格输出。n<=8。

下面贴出源码:

package cn.zimo.algorithm;import java.util.Scanner;/*** 蛇形填数* @author 子墨* @date 2018年5月2日 上午10:58:15*/
public class Demo18 {public static void main(String[] args) {final int n=new Scanner(System.in).nextInt();int[][] a=new int[n][n];int x,y;int tot=1;x=0;y=n-1;a[x][y]=1;while(tot<n*n) {while(x+1<n&&(a[x+1][y]==0)) {a[++x][y]=++tot;}while(y-1>=0&&(a[x][y-1]==0)) {a[x][--y]=++tot;}while(x-1>=0&&(a[x-1][y]==0)) {a[--x][y]=++tot;}while(y+1<n&&(a[x][y+1]==0)) {a[x][++y]=++tot;}}for(int i=0;i<n;i++) {for(int j=0;j<n;j++) {System.out.printf("%4d",a[i][j]);}System.out.println();}}
}

附上另外一种优雅的解法:

package cn.zimo.algorithm;import java.util.Scanner;public class Demo18 {public static void main(String[] args) {Scanner in = new Scanner(System.in);int n = in.nextInt();if (n < 1) {return;}int a[][] = new int[n][n];dfs(a, 0, n - 1, 1);print(a);}private static void print(int[][] a) {for (int i = 0; i < a.length; i++) {for (int j = 0; j < a[i].length; j++) {System.out.printf("%4d", a[i][j]);}System.out.println();}System.out.println();}private static void dfs(int[][] a, int r, int c, int num) {a[r][c] = num;// 下if (r + 1 < a.length && a[r + 1][c] == 0) {dfs(a, r + 1, c, num + 1);}// 左if (c - 1 >= 0 && a[r][c - 1] == 0) {dfs(a, r, c - 1, num + 1);}// 上if (r - 1 >= 0 && a[r - 1][c] == 0) {dfs(a, r - 1, c, num + 1);}// 右,一轮之后应该封口if (c + 1 < a[r].length && a[r][c + 1] == 0) {for (int i = c + 1; a[r][i] == 0; i++) {a[r][i] = ++num;c = i;}// 下一轮if (r + 1 < a.length && c - 1 >= 0 && a[r + 1][c] == 0) {// print(a);dfs(a, r + 1, c, num + 1);}}}
}