# PTA 7-8 卡片邻居游戏 (50 分) Java作业

2021-05-19

## 原题

3
1 2 3 4
6 4 3 3
4 3 7 4


4 3 7 4 6 4 3 3 1 2 3 4


## 题解

import java.util.*;

public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
NumberCard nc = new NumberCard(sc);
CardGame cg = new CardGame(sc);
int num = cg.getNum();
for (int i = 0 ; i < num; i++) {
nc.scan();
cg.insertCard(nc);
}
cg.print();
sc.close();
}
}

class NumberCard {
private int up, down, left, right;
private Scanner sc;
public NumberCard() {}
public NumberCard(Scanner _sc) {
sc = _sc;
}
public void set(NumberCard c) {
up = c.up; down = c.down; left = c.left; right = c.right;
}
public void rotate() {
int tmp = up;
up = left; left = down; down = right; right = tmp;
}
public int getLeft() {
return left;
}
public int getRight() {
return right;
}
public int getUp() {
return up;
}
public int getDown() {
return down;
}
public void print() {
System.out.printf("%d %d %d %d", up, right, down, left);
}
public void scan() {
up = sc.nextInt();
right = sc.nextInt();
down = sc.nextInt();
left = sc.nextInt();
}
}

class CardGame {
private int num;
private NumberCard[] cards;
private Scanner sc;
private int pos;

public CardGame(Scanner _sc) {
sc = _sc;
num = sc.nextInt();
cards = new NumberCard[num];
pos = -1;
}
public int getIndexForFit(NumberCard c) {
if (pos == -1) return 0;
if (c.getRight() == cards[0].getLeft()) return 0;

int _pos;
for (_pos = 1 ; _pos <= pos; _pos++) {
if (c.getLeft() == cards[_pos - 1].getRight() && c.getRight() == cards[_pos].getLeft())
break;
}
if (_pos > pos && c.getLeft() != cards[pos].getRight()) return -1;
return _pos;
}
public boolean insertCard(NumberCard c) {
int _pos = getIndexForFit(c);
if (_pos == -1) return false;

pos++;
cards[pos] = new NumberCard();
for (int i = pos; i > _pos; i--) {
cards[i].set(cards[i-1]);
}
cards[_pos].set(c);
return true;
}
public int getNum() {
return num;
}
public void print() {
for (int i = 0; i <= pos; i++) {
if (i > 0) System.out.print(" ");
cards[i].print();
}
}
}


by SDUST weilinfox

posted @ 2021-05-19 13:45  八衛門狸  阅读(72)  评论(0编辑  收藏  举报