藍橋杯--回形取數

問題描述
  回形取數就是沿矩陣的邊取數,若當前方向上無數可取或已經取過,則左轉90度。一開始位於矩陣左上角,方向向下。
輸入格式
  輸入第一行是兩個不超過200的正整數m, n,表示矩陣的行和列。接下來m行每行n個整數,表示這個矩陣。
輸出格式
  輸出只有一行,共mn個數,爲輸入矩陣回形取數得到的結果。數之間用一個空格分隔,行末不要有多餘的空格。
樣例輸入
3 3
1 2 3
4 5 6
7 8 9
樣例輸出
1 4 7 8 9 6 3 2 5
樣例輸入
3 2
1 2
3 4
5 6
樣例輸出

1 3 5 6 4 2


運行超時-------


package com.xjj.lanqiao;

import java.util.Scanner;

public class Lq2_25 {
	public static int m;
	public static int n;
	public int[][] book = new int[m][n];
	
	public void print(int[][] a, int st, int sy){
		int[][] next = 	 {{1,0},	//向下走
						  {0,1},	//向右走
						  {-1,0},	//向上走
						  {0,-1}};	//向左走
		int x = st, y = sy,k;
		int sum = m * n;
		book[x][y] = 1;
		System.out.print(a[x][y] + " ");
		
		while(sum != 1){
			for(k = 0; k <= 3; k++){
				x = x + next[k][0];
				y = y + next[k][1];
				if (sum == 1) {
					break;
				}
				while(x >= 0 && x < m && y >= 0 && y < n && book[x][y] == 0){
					System.out.print(a[x][y] + " ");
					book[x][y] = 1;
					sum--;
					
					x = x + next[k][0];
					y = y + next[k][1];
				}
				x = x - next[k][0];
				y = y - next[k][1];
			}
		}
	}

	public static void main(String[] args) {
		System.out.println();
		Scanner scanner = new Scanner(System.in);
		m = scanner.nextInt();
		n = scanner.nextInt();
		
		int[][] a = new int[m][n];
		for(int i = 0; i < m; i++)
			for(int j = 0; j < n; j++){
				a[i][j] = scanner.nextInt();
			}

		Lq2_25 lq = new Lq2_25();
		lq.print(a, 0, 0);

	}

}

發佈了58 篇原創文章 · 獲贊 3 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章