字幕旋转游戏的算法题 POJ 3752


字幕旋转游戏

字母旋转游戏,POJ算法题,地址:http://poj.org/problem?id=3752

给定两个整数M,N,生成一个M*N的矩阵,矩阵中元素取值为A至Z的26个字母中的一个,A在左上角,其余各数按顺时针方向旋转前进,依次递增放置,当超过26时又从A开始填充。例如,当M=5,N=8时,矩阵中的内容如下:

A   B   C   D   E   F   G   H

V   W   X   Y   Z   A   B   I

U   J   K   L   M   N   C   J

T   I   H   G   F   E   D   K

S   R   Q   P   O   N   M   L

输入:

M为行数,N为列数,其中M,N都为大于0的整数。

输出:

分行输出相应的结果

样例输入:

4 9

样例输出

A   B   C   D   E   F   G   H   I

V   W   X   Y   Z   A   B   C   J

U   J   I   H   G   F   E   D   K

T   S   R   Q   P   O   N   M   L

通过代码:

import java.util.Scanner;

public class Main {

	public static int index = 0;

	public static char s[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I',
			'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
			'W', 'X', 'Y', 'Z' };

	public static int index_s = 0;

	public static final int MAXN = 100;

	public static char _m[][] = new char[MAXN][MAXN];

	public static boolean mark[][] = new boolean[MAXN][MAXN];

	public static int m;

	public static int n;

	public static Scanner cin = new Scanner(System.in);

	public static int i;

	public static int j;

	public static void main(String args[]) {
		m = cin.nextInt();
		n = cin.nextInt();
		i = 0;
		j = 0;
		init();
		go_to_right();
		for(i = 0; i < m; ++ i){
			System.out.print("   ");
			for(j = 0; j < n; ++ j){
				System.out.print(_m[i][j]+"   ");
			}
			System.out.println();
		}
	}

	public static void go_to_right(){
		while(j < n && !mark[i][j]){
			mark[i][j] = true;
			_m[i][j] = s[index_s];
			++ index_s;
			if(index_s == 26){
				index_s = 0;
			}
			++ j;
			++ index;
		}
		if(index == m*n){
			return;
		}
		-- j;
		++ i;
		go_to_down();
	}

	public static void go_to_down(){
		while(i < m && !mark[i][j]){
			mark[i][j] = true;
			_m[i][j] = s[index_s];
			++ index_s;
			if(index_s == 26){
				index_s = 0;
			}
			++ i;
			++ index;
		}
		if(index == m*n){
			return;
		}
		-- i;
		-- j;
		go_to_left();
	}

	public static void go_to_left(){
		while(j >=0 && !mark[i][j]){
			mark[i][j] = true;
			_m[i][j] = s[index_s];
			++ index_s;
			if(index_s == 26){
				index_s = 0;
			}
			-- j;
			++ index;
		}
		if(index == m*n){
			return;
		}
		++ j;
		-- i;
		go_to_up();
	}

	public static void go_to_up(){
		while(i >= 0 && !mark[i][j]){
			mark[i][j] = true;
			_m[i][j] = s[index_s];
			++ index_s;
			if(index_s == 26){
				index_s = 0;
			}
			-- i;
			++ index;
		}
		if(index == m*n){
			return;
		}
		++ i;
		++ j;
		go_to_right();
	}

	public static void init(){
		int i;
		int j;
		for(i = 0; i < MAXN; ++ i){
			for(j = 0; j < MAXN; ++ j){
				mark[i][j] = false;
			}
		}
	}

}