順時針打印矩陣

題目描述

對於一個矩陣,請設計一個算法從左上角(mat[0][0])開始,順時針打印矩陣元素。 給定int矩陣mat,以及它的維數n x m,請返回一個數組,數組中的元素爲矩陣元素的順時針輸出。java

測試樣例

[[1, 2], [3, 4]], 2, 2

返回:[1, 2, 4, 3]

解題思路

要控制好每次的轉向算法

解決方案

import java.util.*;

public class Printer {
	private enum Direction {
		RIGHT, DOWN, LEFT, UP;
	}
    
    public int[] clockwisePrint(int[][] mat, int n, int m) {

		HashSet<String> set = new HashSet<String>();

		int[] rs = new int[n * m];

		Direction dir = Direction.RIGHT;
		int i = 0, j = -1;
		int idx = 0;

		while (set.size() < rs.length) {

			if (dir == Direction.RIGHT) {
				if (j < m - 1
						&& !set.contains(String.format("%d,%d", i, j + 1))) {
					j++;
					rs[idx++] = mat[i][j];
					set.add(String.format("%d,%d", i, j));
				} else {
					dir = Direction.DOWN;
				}
			}

			else if (dir == Direction.DOWN) {
				if (i < n - 1
						&& !set.contains(String.format("%d,%d", i + 1, j))) {
					i++;
					rs[idx++] = mat[i][j];
					set.add(String.format("%d,%d", i, j));
				} else {
					dir = Direction.LEFT;
				}
			}

			else if (dir == Direction.LEFT) {
				if (j > 0 && !set.contains(String.format("%d,%d", i, j - 1))) {
					j--;
					rs[idx++] = mat[i][j];
					set.add(String.format("%d,%d", i, j));
				} else {
					dir = Direction.UP;
				}
			}

			else if (dir == Direction.UP) {
				if (i > 0 && !set.contains(String.format("%d,%d", i - 1, j))) {
					i--;
					rs[idx++] = mat[i][j];
					set.add(String.format("%d,%d", i, j));
				} else {
					dir = Direction.RIGHT;
				}
			}
		}

		return rs;
	
    }
}

測試樣例

import org.junit.Test;
import static org.junit.Assert.*;

public class ClockwisePrinterTest {
	private static ClockwisePrinter obj = new ClockwisePrinter();

	@Test
	public void test1() {
		int[][] mat = new int[][] { { 1, 2 }, { 3, 4 } };
		int n = 2, m = 2;
		int[] r = new int[] { 1, 2, 4, 3 };
		assertArrayEquals(r, obj.clockwisePrint(mat, n, m));
	}

	@Test
	public void test2() {
		int[][] mat = new int[][] { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
		int n = 3, m = 3;
		int[] r = new int[] { 1, 2, 3, 6, 9, 8, 7, 4, 5 };
		assertArrayEquals(r, obj.clockwisePrint(mat, n, m));
	}

	@Test
	public void test3() {
		int[][] mat = new int[][] { { 1, 2, 3, 4 }, { 5, 6, 7, 8 },
				{ 9, 10, 11, 12 }, { 13, 14, 15, 16 } };
		int n = 4, m = 4;
		int[] r = new int[] { 1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5, 6, 7,
				11, 10 };
		assertArrayEquals(r, obj.clockwisePrint(mat, n, m));
	}
}
相關文章
相關標籤/搜索