【基礎練習 ⊇ 數論】B004_回形取數(枚舉)

一、題目描述

回形取數就是沿矩陣的邊取數,若當前方向上無數可取或已經取過,則左轉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

二、題解

方法一:模擬

* 超時錯誤:

import java.util.*;
public class Main{  	  
    public static void main(String[] args) {  
        Scanner sc = new Scanner(System.in);
        int R = sc.nextInt();
		int C = sc.nextInt();
		
		int[][] grid = new int[R][C];
		for (int i = 0; i < R; i++)
		for (int j = 0; j < C; j++) {
			grid[i][j] = sc.nextInt();
		}
		int count = 0;
		int x = 0, y = 0;

		System.out.print(grid[0][0] + " ");
		count++;
		while (count < R * C) {
			while (x+1 < R && grid[x+1][y] != -1) {
				count++;
				System.out.print(grid[++x][y]+ " ");
				grid[x][y] = -1;
			}
			while (y+1 < C && grid[x][y+1] != -1) {
				count++;
				System.out.print(grid[x][++y]+ " ");
				grid[x][y] = -1;
			}
			while (x-1 >= 0 && grid[x-1][y] != -1) {
				count++;
				System.out.print(grid[--x][y]+ " ");
				grid[x][y] = -1;
			}
			while (y-1 > 0 && x != 0 && grid[x][y-1] != -1) {
				count++;
				System.out.print(grid[x][--y] + " ");
				grid[x][y] = -1;
			}
		}
		System.out.println();
		sc.close();
    }
}

複雜度分析

  • 時間複雜度:O(n)O(n)
  • 空間複雜度:O(1)O(1)

給數組增加一圈,然後錯開第一個 while 循環的 +1

方法二:

算法

  • count 記錄遍歷個數,x 記錄行數,y 記錄列數。
  • 首先向下取值。
  • 然後向右,向上,向左,有向下。

* 邊界出錯:

  • Q1:count 爲什麼是 < R × C ?
    A1:因爲最後取完最後一個數,count 纔等於 R × C,所以想要退出循環
  • Q2:爲什麼需要將數組增加一環?
    A2:邊界點容易處理。比如一開始向下時。
import java.util.*;
public class Main{  	  
    public static void main(String[] args) {  
        Scanner sc = new Scanner(System.in);
        int R = sc.nextInt();
		int C = sc.nextInt();
		
		int[][] grid = new int[R+1][C+1];
		for (int i = 1; i <= R; i++)
		for (int j = 1; j <= C; j++) {
			grid[i][j] = sc.nextInt();
		}
		int count = 0;
		int x = 0, y = 1;

		while (count < R * C) {
			while (x+1 <= R && grid[x+1][y] != -1) {
				count++;
				System.out.print(grid[++x][y]+ " ");
				grid[x][y] = -1;
			}
			while (y+1 <= C && grid[x][y+1] != -1) {
				count++;
				System.out.print(grid[x][++y]+ " ");
				grid[x][y] = -1;
			}
			while (x-1 > 0 && grid[x-1][y] != -1) {
				count++;
				System.out.print(grid[--x][y]+ " ");
				grid[x][y] = -1;
			}
			while (y-1 > 0 && grid[x][y-1] != -1) {
				count++;
				System.out.print(grid[x][--y] + " ");
				grid[x][y] = -1;
			}
		}
		System.out.println();
		sc.close();
		return;
    }
}

複雜度分析

  • 時間複雜度:O(n)O(n)
  • 空間複雜度:O1()O1()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章