problems / 219

ASCII Island Bipartite Check

medium bipartite bfs dfs graphs 1000 ms · 256 MB

ASCII Island Bipartite Check

You have an ASCII map of an island with different terrain types. Each character represents a terrain type. Terrain regions are connected components of cells with the same character, connected orthogonally (up/down/left/right, not diagonally).

Two regions are adjacent if they share an edge (not just a corner). We can think of the regions as nodes in a graph, with edges between adjacent regions.

Your task: Determine if the region graph is bipartite, meaning we can assign one of two colors to each region such that no two adjacent regions have the same color.

Input

The first line contains r and c (1 ≤ r, c ≤ 300), the dimensions of the map.

The next r lines each contain c characters, representing the terrain map. Characters are lowercase letters a–z.

Output

Print YES if the region graph is bipartite, or NO otherwise.

Notes

Two regions are adjacent if they share an orthogonal edge. A single region may be adjacent to itself indirectly (for example, an a region with a b region between two parts of the a region), but this is considered a normal edge in the graph.

In the second example, there is one region of a and one region of b. They are adjacent, so the graph is bipartite.

Example 1

Input

2 2
ab
ba

Output

YES

Example 2

Input

3 3
acb
cab
bca

Output

NO

Hints · reveal one at a time if you're stuck

Hint 1

The nodes of this graph aren't cells, they're whole regions. Before you can say which regions touch, what do you need to know about every cell?

Hint 2

Give every cell a region id with a flood fill (BFS or DFS over orthogonal neighbours with the same letter). Then any two neighbouring cells with different ids are an edge between those two regions. On a 300×300 map, an iterative BFS avoids very deep recursion.

Hint 3

"Bipartite" means the regions can be 2-coloured so that touching regions differ: try colouring the region graph and look for a conflict. Remember it may have several connected components.

report an issue Prefer your own editor? sooks prep 219 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.