Catherine Gasnier
BAN USER
I wonder:
Is this a plus?
0 0 0 0 1 0 0 0 0
0 1 1 0 1 0 1 1 0
0 0 0 0 1 0 1 1 0
0 0 0 0 1 0 0 0 0
1 1 1 1 1 1 1 1 1
0 0 0 0 1 0 0 0 0
0 0 0 0 1 0 0 0 0
0 0 0 0 1 0 0 1 0
1 0 0 0 1 0 0 0 0
that is to say a "plus" would be defined as one horizontal segment of only 1s of size 2*i+1 and one vertical segment of only 1s of size 2*i+1 intersecting at their center.
Or only that kind of stuff is a plus?
0 0 0 0 1 0 0 0 0
0 0 0 0 1 0 0 0 0
0 0 0 0 1 0 0 0 0
0 0 0 0 1 0 0 0 0
1 1 1 1 1 1 1 1 1
0 0 0 0 1 0 0 0 0
0 0 0 0 1 0 0 0 0
0 0 0 0 1 0 0 0 0
0 0 0 0 1 0 0 0 0
If that's the second, it is a bit more complicated with a sparse matrix... So I'll assume it is the first.
I represent the sparse matrix simply as the set of positions where the 1s are.
package exercices;
import java.util.*;
public class LargestPlusFinder {
public static Plus findLargestPlus(Set<Position> board) throws NoPlusFoundException {
AdjacencyGraph adjacencyGraph = new AdjacencyGraph(board);
return adjacencyGraph.findLargestPlus();
}
private static class AdjacencyGraph {
Map<Position, Vertex> vertices;
Set<Vertex> potentialPlusCenters;
public AdjacencyGraph(Set<Position> board) {
vertices = new HashMap<>();
potentialPlusCenters = new HashSet<>();
for (Position position: board) {
addPosition(position);
}
}
private void addPosition(Position position) {
if (vertices.containsKey(position)) {
return;
}
Vertex newVertex = new Vertex(position);
makeEdgesForNewVertex(newVertex);
if (newVertex.isPotentialPlusCenter()) {
potentialPlusCenters.add(newVertex);
}
vertices.put(position, newVertex);
}
private void makeEdgesForNewVertex(Vertex newVertex) {
Position position = newVertex.getPosition();
for (Direction direction: Direction.values()) {
if (vertices.containsKey(position.getAdjacentPosition(direction))) {
Vertex adjacentVertex = vertices.get(position.getAdjacentPosition(direction));
makeBidirectionalEdge(newVertex, direction, adjacentVertex);
if (adjacentVertex.isPotentialPlusCenter()) {
potentialPlusCenters.add(adjacentVertex);
}
}
}
}
private void makeBidirectionalEdge(Vertex v1, Direction direction, Vertex v2) {
v1.add(direction, v2);
v2.add(opposite(direction), v1);
}
public Plus findLargestPlus() throws NoPlusFoundException {
if (vertices.isEmpty()) {
throw new NoPlusFoundException();
}
int maxEdgeLength = 0;
Position maxPlusCenter = vertices.keySet().iterator().next();
for (Vertex v: potentialPlusCenters) {
Plus plus = getPlusAt(v); // there is at least a plus of edge size 0 at v
if (plus.getEdgeLength() > maxEdgeLength) {
maxEdgeLength = plus.getEdgeLength();
maxPlusCenter = plus.getCenter();
}
}
return new Plus(maxPlusCenter, maxEdgeLength);
}
private Plus getPlusAt(Vertex v) {
Queue<Exploration> q = new LinkedList<>();
for (Direction d: Direction.values()) {
q.add(new Exploration(d, v.getAdjacent(d), 1));
}
Exploration e = q.poll();
while (e != null) {
Direction direction = e.getDirection();
Vertex exploredVertex = e.getVertex();
int currentEdgeLength = e.getReachedEdgeLength();
if (exploredVertex.getAdjacent(direction) != null) {
q.add(new Exploration(direction, exploredVertex.getAdjacent(direction), currentEdgeLength + 1));
} else {
// Exploration stops here
return (new Plus(v.getPosition(), currentEdgeLength));
}
e = q.poll();
}
throw new ProgrammingErrorException();
}
private static class Vertex {
final Position position;
Map<Direction, Vertex> adjacentVertices;
public Vertex(Position position) {
this.position = position;
adjacentVertices = new HashMap<>();
}
public void add(Direction d, Vertex v) {
adjacentVertices.put(d, v);
}
public boolean isPotentialPlusCenter() {
return adjacentVertices.size() == Direction.values().length;
}
public Position getPosition() {
return position;
}
public Vertex getAdjacent(Direction d) {
return adjacentVertices.get(d);
}
}
private static class Exploration {
Direction direction;
Vertex vertex;
int reachedEdgeLength;
public Exploration(Direction direction, Vertex vertex, int reachedEdgeLength) {
this.direction = direction;
this.vertex = vertex;
this.reachedEdgeLength = reachedEdgeLength;
}
public Direction getDirection() {
return direction;
}
public Vertex getVertex() {
return vertex;
}
public int getReachedEdgeLength() {
return reachedEdgeLength;
}
}
}
private static class Position {
int i;
int j;
public Position(int i, int j) {
this.i = i;
this.j = j;
}
public Position getAdjacentPosition(Direction d) {
switch (d) {
case UP:
return new Position(i-1, j);
case DOWN:
return new Position(i+1, j);
case LEFT:
return new Position(i, j-1);
case RIGHT:
return new Position(i, j+1);
default:
throw new ProgrammingErrorException();
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Position position = (Position) o;
return i == position.i &&
j == position.j;
}
@Override
public int hashCode() {
return Objects.hash(i, j);
}
@Override
public String toString() {
return "Position{" +
"i=" + i +
", j=" + j +
'}';
}
}
private static class Plus {
private Position center;
private int edgeLength;
public Plus(Position center, int edgeLength) {
this.center = center;
this.edgeLength = edgeLength;
}
public Position getCenter() {
return center;
}
public int getEdgeLength() {
return edgeLength;
}
@Override
public String toString() {
return "(" + i + ", " + j + ")";
}
}
private enum Direction {UP, DOWN, RIGHT, LEFT}
private static Direction opposite(Direction d) {
switch (d) {
case UP:
return Direction.DOWN;
case DOWN:
return Direction.UP;
case LEFT:
return Direction.RIGHT;
case RIGHT:
return Direction.LEFT;
default:
throw new ProgrammingErrorException();
}
}
private static class NoPlusFoundException extends Exception {}
private static class ProgrammingErrorException extends RuntimeException {}
public static void main(String[] args) {
Set<Position> board = new HashSet<>();
board.add(new Position(100, 100));
board.add(new Position(101, 100));
board.add(new Position(102, 100));
board.add(new Position(99, 100));
board.add(new Position(98, 100));
board.add(new Position(100, 101));
board.add(new Position(100, 102));
board.add(new Position(100, 99));
board.add(new Position(100, 98));
board.add(new Position(99, 98));
try {
Plus maxPlus = findLargestPlus(board);
System.out.println(maxPlus);
} catch (NoPlusFoundException e) {
System.out.println("No plus in board.");
}
}
}
Repcinderellagale, Financial Application Engineer at Continental
Working as a Forecasting Analyst at Thorofare for more than three years. There, I am responsible for developing detailed business ...
RepNoraLillian, Applications Developer at Coupondesh
Nora, working as a ghostwriter with a history in manuscript development, proofreading, and editing, I apply with enthusiasm for this ...
RepAre you searching the best and strong Mantra to remove black magic. Here the best and the most powerful Astromagic ...
RepWhyable is an agile team of Software Specialists with vast experience across multiple languages.We will help you to define ...
RepZoeParker, Java Experienced at Abs india pvt. ltd.
I am Zoe , a Security Analyst with a record of success in completing financial market research and conducting earnings estimates ...
Repkassacraven, Java Experienced at Brainware
Kassa , an Outgoing a Travel Consultant with over 3 years of experience in delivering professional travel and tourism-related services focusing ...
RepHey, my name is DooreMee and I completed all my study from California. And Nowadays I am working as a ...
Replillianrperkins66, Android test engineer at ABC TECH SUPPORT
I'm Lillian Perkins, and I'm a studio camera operator. A studio camera operator Main work includes operating cranes ...
Repyalendatopi, Dev Lead at Alliance Global Servies
I am Yalenda , a video editor with 3+ years of experience, skilled in Premiere Pro. Seeking position with Weingarten's ...
RepLopezKape, Applications Developer at A9
Lopez , an Outgoing Headhunter with a comprehensive background of client satisfaction in finding and recruiting top talent for various organizations ...
Repherminanmuller87, Animator at 247quickbookshelp
Hello,I am a literacy teacher. I completed my degree from Chicago and now am a literacy teacher in a ...
RepRuzilStaker, Java Freshers at Digital Merkating
Ruzil , a Publicity Specialist with over four years in PR. Also a communicator adept at managing all public relations efforts ...
RepMacHeist, Data Scientist at British Telecom
Mac, a Desktop Publishing Specialist at VitaGrey, where I provide document formatting and publishing support to a wide variety of ...
Repirenereed98, Discount Furniture Showcase at Physical therapist aid
I'm a Physical advisor helping working at Discount Furniture Showcase . I'm likewise a film buff who partakes in ...
RepWant to know how to protect from black magic? Guru Ji is the world’s famous astrologer and he has ...
RepKoriScott, abc at Omli
Licensed mechanical maintenance engineer with extensive practical experience working with diverse systems and equipment. Solid professional knowledge base built upon ...
Repaliciaable183, Analyst at 247quickbookshelp
I am an agent contract clerk who is responsible for handling the recruitment process. I advertise the vacancies for agents ...
Reprudystake, Game Programmer at BrowserStack
I am Rudy , a physical therapist with extensive knowledge of sports injuries and therapy . Strong background in athletic coaching and ...
RepDonnaTyler, HR Executive freshers at Bloomberg LP
I am Donna , a travel counselor who advises clients on travel options and tour packages, makes bookings , prepares tickets and ...
RepMillaSoth, Intern at ADP
I am Milla , a dedicated Emergency Response Technician regarded for performing advanced medical procedures with a high degree of accuracy ...
RepBlack magic removal mantra is the best remedy for you. Magic master provides 100% guaranteed solution.This power gives you ...
RepAidenKim, business planner manager at GPU
Expert business strategist with a sound understanding of organizational development and sales. Persuasive negotiator who uses integrity and professionalism in ...
Rephugaliuli, Nurse at 8x8
Registered nurse with experience in delivering quality care to patients. Professional with more than 3 years in emergency room care ...
Repandrealmoore45, Analyst at 247quickbookshelp
My name is Andrea and I Live in california. I like to read articles from some interesting topics.And today ...
RepHad a brief career donating velcro in Africa. Spent several years training sock monkeys in Pensacola, FL. Gifted in working ...
RepHelenHinkley, Accountant at 8x8
Dedicated English-Mandarin Chinese translator with years of experience working in professional and scientific communities. I am passionate about how to ...
RepAlisonjaeger755, Data Engineer at Accolite software
I am work in Telecom line in IDEA company. I am data operator and Engineer in back end in Idea ...
RepDasiySmith, abc at 247quickbookshelp
I am versati;e architect, accomplished at designing commercial and residential structures of varying styles and purpose.I was met ...
RepIsabellaJones, abc at 8x8
Extensive experience of 3 years in network architecture and application requirements for corporate data and voice networks, planning, designing and ...
RepAnayAllen, Analyst at 8x8
Exceptional knowledge of mathematical concepts, accounting and finance topics, tax code, and banking principles.I like the topic of how ...
Repmonamore609, Android test engineer at Cisco Systems
Data entry clerks are responsible for inputting a high volume of data from multiple sources into a database, ensuring that ...
Repwastonlare, Java Developer at Broadsoft
Waston , an executive in the finance and accounting area of the industry with expertise in teaching, training and managing my ...
RepPrishaDavin, abc at 8x8
I promote and provide extraordinary internal external guest services, answer questions, offer information, and provide assistance in a courteous manner ...
Repbenaryhell3454, Blockchain Developer at A9
Working as a carpet installer at Simple Solutions is almost 10 years . Here I daily meet new people and learn ...
Repjacquelinejlopes48, Analyst at 247quickbookshelp
Hey, I am Jacqueline and I am a court reporter.I had heard a lot about Vashikaran Specialist,now I ...
Repbrianlwarren596, Android Engineer at 247quickbookshelp
Hey my name is BrainWarren and I am working as an Interpreter.my main work is Interpreters and translators convert ...
RepDukeRollin, Java Experienced at AMD
Duke, a Qualified psychiatrist with seven years of experience effectively treating patients with a wide range of conditions with a ...
RepSimonPister, Blockchain Developer at Absolute Softech Ltd
Simon , a food scientist , records the Tracking status of all existing ingredients during the review and updating process and communicates ...
In fact, as a node, I am a leaf i.i.f. the node following me in the preorder traversal array is greater than the first of my ancestors which is greater than me. So while traversing the BST, we need to maintain the stack of the ancestors that are greater than the current node.
In java, something like:
- Catherine Gasnier February 17, 2017