A tile wall has H rows and W columns, and each cell holds one lowercase English letter. A pattern has h rows and w columns, and each cell holds one lowercase English letter or ?. A ? in the pattern matches any letter, and a lowercase letter in the pattern matches only the same letter. The pattern may be tried unturned (0 degrees), or turned clockwise by 90, 180 or 270 degrees. A pattern turned clockwise by 90 degrees has w rows and h columns. Row i of the turned pattern is the string formed by reading the h letters in column i of the original pattern from the bottom row up to the top row. 180 degrees is the 90-degree turn done twice, and 270 degrees is the 90-degree turn done three times. When the top-left cell of the pattern turned by some angle is placed on row r, column c of the wall, the pattern stays inside the wall, and every cell of the pattern matches the wall cell under it, we say the pattern matches at (r, c) with that angle. Given q patterns, for each pattern choose, among all ways it matches, the one with the smallest r; if several remain, the one with the smallest c; if several still remain, the one with the smallest angle. Print r, c and the angle of the chosen way on one line, separated by single spaces. Rows and columns are numbered from 1. The angle is one of 0, 90, 180, 270, written as a plain number. If the pattern matches at no position with any angle, print -1. A pattern may be larger than the wall. The first line gives H and W separated by a single space, and the next H lines each give a string of length W. The next line gives q. For each pattern, the first line gives h and w separated by a single space, and the next h lines each give a string of length w. Try solving it with a function that returns the first matching (row, column, angle). Grading looks only at the output.
Input
1 ≤ H, W ≤ 20. 1 ≤ q ≤ 10. 1 ≤ h, w ≤ 20. The wall strings contain only lowercase English letters, the pattern strings only lowercase English letters and ?, with no spaces
Output
For each pattern, r c angle or -1, one per line
Example 1 · stdin
4 5
catso
odogt
goats
tacdo
4
2 1
t
a
1 3
cat
2 2
ao
t?
1 2
xy
stdout
1 2 90
1 1 0
2 3 270
-1
Example 2 · stdin
1 3
abc
2
3 1
a
b
c
1 4
abca
stdout
1 1 270
-1
main.py
Error List00F8 ↓ · ⇧F8 ↑
Input (stdin)
When you run, these lines are fed to input()/stdin in order (the program doesn't stop to ask).
$ Ready
Open this on a computer to write and run code. On mobile you can read the problem and the solutions.
In other languagesShow solutions by language · 8 languages
Split the work into three functions: rotate, which returns a new pattern turned clockwise; fits, which returns true or false for one position; and find, which returns the first matching (row, column, angle). find has to return three values or 'nothing', and that looks different in each language. Python returns a tuple (r, c, d) or None, JS an array or null, TS writes the return type [number, number, number] | null, Java returns int[] or null, C# a nullable tuple (int r, int c, int angle)?, C++ std::optional<std::array<int, 3>>, and C returns true or false and writes the three values through pointer arguments (int *row and so on). Craykon returns a list [r, c, angle] or null. Trap 1: once a position matches, return at once (Craykon return) to leave all three nested loops together. break (Craykon break) ends only the innermost loop, so the outer loops keep going and a later match overwrites the answer (cat in example 1 gives 4 1 180 instead of 1 1 0). Java, JS and TS have a labeled break outer; and C, C++ and C# have goto, but Python and Craykon have neither, so moving the search into a function and returning is the cleanest way. Trap 2: inside the loop of fits, don't return true after looking at only the first cell. Return false as soon as a cell differs, and true only after the loop has finished. Trap 3: a pattern turned by 90 or 270 degrees swaps its height and width (h×w → w×h). If the range of positions is set from h and w before turning, you miss positions where a tall pattern fits lying down, as in example 2. Check whether it leaves the wall using the turned pattern's size. Trap 4: row i of the clockwise-turned pattern is column i of the original read from bottom to top. Turning counterclockwise swaps 90 and 270 degrees (t/a in example 1 gives 1 2 270). Trap 5: putting the angle in the outermost loop finds 'smallest angle first' instead of 'topmost position first'. The order in which the loops nest is the order in which the answer is chosen. Trap 6: always write what to return when nothing was found. In Java and C# a missing final return null; is a compile error; Python returns None by itself and JS returns undefined. When a Craykon function ends without return, the value it gives does not compare equal to null, so the check spot == null is passed over and the program stops while reading spot[0]. Write return null; at the end.
Pythonmain.py · 53 lines
import sysdef rotate(pattern): """무늬를 시계 방향으로 90도 돌린 새 무늬를 돌려준다.""" h, w = len(pattern), len(pattern[0]) return ["".join(pattern[h - 1 - j][i] for j in range(h)) for i in range(w)]def fits(wall, pattern, r, c): """무늬의 왼쪽 위를 벽의 (r, c)에 댔을 때 모든 칸이 맞는가.""" h, w = len(pattern), len(pattern[0]) if r + h > len(wall) or c + w > len(wall[0]): return False for i in range(h): for j in range(w): if pattern[i][j] != "?" and pattern[i][j] != wall[r + i][c + j]: return False return Truedef find(wall, pattern): """처음 맞는 (줄, 칸, 각)을 돌려준다. 없으면 None.""" turns = [pattern] for _ in range(3): turns.append(rotate(turns[-1])) for r in range(len(wall)): for c in range(len(wall[0])): for k in range(4): if fits(wall, turns[k], r, c): return r + 1, c + 1, k * 90 return Nonedef main(): data = sys.stdin.read().split() at = 0 height, width = int(data[0]), int(data[1]) wall = data[2:2 + height] at = 2 + height q = int(data[at]) at += 1 out = [] for _ in range(q): h = int(data[at]) pattern = data[at + 2:at + 2 + h] at += 2 + h found = find(wall, pattern) out.append("-1" if found is None else "%d %d %d" % found) print("\n".join(out))main()
JavaScriptmain.js · 53 lines
const data = require("fs").readFileSync(0, "utf8").split(/\s+/).filter((s) => s !== "");// 무늬를 시계 방향으로 90도 돌린 새 무늬를 돌려준다function rotate(pattern) { const h = pattern.length, w = pattern[0].length; const turned = []; for (let i = 0; i < w; i++) { let row = ""; for (let j = 0; j < h; j++) row += pattern[h - 1 - j][i]; turned.push(row); } return turned;}// 무늬의 왼쪽 위를 벽의 (r, c)에 댔을 때 모든 칸이 맞는가function fits(wall, pattern, r, c) { const h = pattern.length, w = pattern[0].length; if (r + h > wall.length || c + w > wall[0].length) return false; for (let i = 0; i < h; i++) { for (let j = 0; j < w; j++) { if (pattern[i][j] !== "?" && pattern[i][j] !== wall[r + i][c + j]) return false; } } return true;}// 처음 맞는 [줄, 칸, 각]을 돌려준다. 없으면 nullfunction find(wall, pattern) { const turns = [pattern]; for (let k = 1; k < 4; k++) turns.push(rotate(turns[k - 1])); for (let r = 0; r < wall.length; r++) { for (let c = 0; c < wall[0].length; c++) { for (let k = 0; k < 4; k++) { if (fits(wall, turns[k], r, c)) return [r + 1, c + 1, k * 90]; } } } return null;}const height = Number(data[0]);const wall = data.slice(2, 2 + height);let at = 2 + height;const q = Number(data[at++]);const out = [];for (let t = 0; t < q; t++) { const h = Number(data[at]); const pattern = data.slice(at + 2, at + 2 + h); at += 2 + h; const found = find(wall, pattern); out.push(found === null ? "-1" : found.join(" "));}console.log(out.join("\n"));
TypeScriptmain.ts · 55 lines
import * as fs from "fs";const data: string[] = fs.readFileSync(0, "utf8").split(/\s+/).filter((s) => s !== "");// 무늬를 시계 방향으로 90도 돌린 새 무늬를 돌려준다function rotate(pattern: string[]): string[] { const h = pattern.length, w = pattern[0].length; const turned: string[] = []; for (let i = 0; i < w; i++) { let row = ""; for (let j = 0; j < h; j++) row += pattern[h - 1 - j][i]; turned.push(row); } return turned;}// 무늬의 왼쪽 위를 벽의 (r, c)에 댔을 때 모든 칸이 맞는가function fits(wall: string[], pattern: string[], r: number, c: number): boolean { const h = pattern.length, w = pattern[0].length; if (r + h > wall.length || c + w > wall[0].length) return false; for (let i = 0; i < h; i++) { for (let j = 0; j < w; j++) { if (pattern[i][j] !== "?" && pattern[i][j] !== wall[r + i][c + j]) return false; } } return true;}// 처음 맞는 [줄, 칸, 각]을 돌려준다. 없으면 nullfunction find(wall: string[], pattern: string[]): [number, number, number] | null { const turns: string[][] = [pattern]; for (let k = 1; k < 4; k++) turns.push(rotate(turns[k - 1])); for (let r = 0; r < wall.length; r++) { for (let c = 0; c < wall[0].length; c++) { for (let k = 0; k < 4; k++) { if (fits(wall, turns[k], r, c)) return [r + 1, c + 1, k * 90]; } } } return null;}const height = Number(data[0]);const wall = data.slice(2, 2 + height);let at = 2 + height;const q = Number(data[at++]);const out: string[] = [];for (let t = 0; t < q; t++) { const h = Number(data[at]); const pattern = data.slice(at + 2, at + 2 + h); at += 2 + h; const found = find(wall, pattern); out.push(found === null ? "-1" : found.join(" "));}console.log(out.join("\n"));
JavaMain.java · 70 lines
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.util.StringTokenizer;public class Main { // 무늬를 시계 방향으로 90도 돌린 새 무늬를 돌려준다 static String[] rotate(String[] pattern) { int h = pattern.length, w = pattern[0].length(); String[] turned = new String[w]; for (int i = 0; i < w; i++) { StringBuilder row = new StringBuilder(); for (int j = 0; j < h; j++) row.append(pattern[h - 1 - j].charAt(i)); turned[i] = row.toString(); } return turned; } // 무늬의 왼쪽 위를 벽의 (r, c)에 댔을 때 모든 칸이 맞는가 static boolean fits(String[] wall, String[] pattern, int r, int c) { int h = pattern.length, w = pattern[0].length(); if (r + h > wall.length || c + w > wall[0].length()) return false; for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { char p = pattern[i].charAt(j); if (p != '?' && p != wall[r + i].charAt(c + j)) return false; } } return true; } // 처음 맞는 {줄, 칸, 각}을 돌려준다. 없으면 null static int[] find(String[] wall, String[] pattern) { String[][] turns = new String[4][]; turns[0] = pattern; for (int k = 1; k < 4; k++) turns[k] = rotate(turns[k - 1]); for (int r = 0; r < wall.length; r++) { for (int c = 0; c < wall[0].length(); c++) { for (int k = 0; k < 4; k++) { if (fits(wall, turns[k], r, c)) return new int[] {r + 1, c + 1, k * 90}; } } } return null; } public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringBuilder all = new StringBuilder(); String line; while ((line = in.readLine()) != null) all.append(line).append('\n'); StringTokenizer st = new StringTokenizer(all.toString()); int height = Integer.parseInt(st.nextToken()); st.nextToken(); String[] wall = new String[height]; for (int r = 0; r < height; r++) wall[r] = st.nextToken(); int q = Integer.parseInt(st.nextToken()); StringBuilder out = new StringBuilder(); for (int t = 0; t < q; t++) { int h = Integer.parseInt(st.nextToken()); st.nextToken(); String[] pattern = new String[h]; for (int i = 0; i < h; i++) pattern[i] = st.nextToken(); int[] found = find(wall, pattern); if (found == null) out.append("-1\n"); else out.append(found[0]).append(' ').append(found[1]).append(' ').append(found[2]).append('\n'); } System.out.print(out); }}
C#Main.cs · 76 lines
using System;using System.Text;class Program{ // 무늬를 시계 방향으로 90도 돌린 새 무늬를 돌려준다 static string[] Rotate(string[] pattern) { int h = pattern.Length, w = pattern[0].Length; var turned = new string[w]; for (int i = 0; i < w; i++) { var row = new StringBuilder(); for (int j = 0; j < h; j++) row.Append(pattern[h - 1 - j][i]); turned[i] = row.ToString(); } return turned; } // 무늬의 왼쪽 위를 벽의 (r, c)에 댔을 때 모든 칸이 맞는가 static bool Fits(string[] wall, string[] pattern, int r, int c) { int h = pattern.Length, w = pattern[0].Length; if (r + h > wall.Length || c + w > wall[0].Length) return false; for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { char p = pattern[i][j]; if (p != '?' && p != wall[r + i][c + j]) return false; } } return true; } // 처음 맞는 (줄, 칸, 각)을 돌려준다. 없으면 null static (int r, int c, int angle)? Find(string[] wall, string[] pattern) { var turns = new string[4][]; turns[0] = pattern; for (int k = 1; k < 4; k++) turns[k] = Rotate(turns[k - 1]); for (int r = 0; r < wall.Length; r++) { for (int c = 0; c < wall[0].Length; c++) { for (int k = 0; k < 4; k++) { if (Fits(wall, turns[k], r, c)) return (r + 1, c + 1, k * 90); } } } return null; } static void Main() { string[] data = Console.In.ReadToEnd().Split((char[])null, StringSplitOptions.RemoveEmptyEntries); int height = int.Parse(data[0]); var wall = new string[height]; Array.Copy(data, 2, wall, 0, height); int at = 2 + height; int q = int.Parse(data[at++]); var output = new StringBuilder(); for (int t = 0; t < q; t++) { int h = int.Parse(data[at]); var pattern = new string[h]; Array.Copy(data, at + 2, pattern, 0, h); at += 2 + h; var found = Find(wall, pattern); if (found == null) output.Append("-1\n"); else output.Append($"{found.Value.r} {found.Value.c} {found.Value.angle}\n"); } Console.Write(output); }}
C++main.cpp · 66 lines
#include <array>#include <iostream>#include <optional>#include <string>#include <vector>using Grid = std::vector<std::string>;// 무늬를 시계 방향으로 90도 돌린 새 무늬를 돌려준다Grid rotate(const Grid& pattern) { int h = pattern.size(), w = pattern[0].size(); Grid turned(w, std::string(h, ' ')); for (int i = 0; i < w; i++) { for (int j = 0; j < h; j++) turned[i][j] = pattern[h - 1 - j][i]; } return turned;}// 무늬의 왼쪽 위를 벽의 (r, c)에 댔을 때 모든 칸이 맞는가bool fits(const Grid& wall, const Grid& pattern, int r, int c) { int h = pattern.size(), w = pattern[0].size(); if (r + h > (int)wall.size() || c + w > (int)wall[0].size()) return false; for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { char p = pattern[i][j]; if (p != '?' && p != wall[r + i][c + j]) return false; } } return true;}// 처음 맞는 {줄, 칸, 각}을 돌려준다. 없으면 std::nulloptstd::optional<std::array<int, 3>> find(const Grid& wall, const Grid& pattern) { std::array<Grid, 4> turns; turns[0] = pattern; for (int k = 1; k < 4; k++) turns[k] = rotate(turns[k - 1]); for (int r = 0; r < (int)wall.size(); r++) { for (int c = 0; c < (int)wall[0].size(); c++) { for (int k = 0; k < 4; k++) { if (fits(wall, turns[k], r, c)) return std::array<int, 3>{r + 1, c + 1, k * 90}; } } } return std::nullopt;}Grid readGrid() { int h, w; std::cin >> h >> w; Grid g(h); for (auto& row : g) std::cin >> row; return g;}int main() { Grid wall = readGrid(); int q; std::cin >> q; while (q-- > 0) { Grid pattern = readGrid(); auto found = find(wall, pattern); if (found) std::cout << (*found)[0] << ' ' << (*found)[1] << ' ' << (*found)[2] << '\n'; else std::cout << "-1\n"; } return 0;}
Cmain.c · 72 lines
#include <stdbool.h>#include <stdio.h>#define MAX 20typedef struct { int h, w; char cell[MAX][MAX + 1];} Grid;/* 무늬를 시계 방향으로 90도 돌린 새 무늬를 돌려준다 */static Grid rotate(const Grid *p) { Grid turned; turned.h = p->w; turned.w = p->h; for (int i = 0; i < turned.h; i++) { for (int j = 0; j < turned.w; j++) turned.cell[i][j] = p->cell[p->h - 1 - j][i]; turned.cell[i][turned.w] = '\0'; } return turned;}/* 무늬의 왼쪽 위를 벽의 (r, c)에 댔을 때 모든 칸이 맞는가 */static bool fits(const Grid *wall, const Grid *p, int r, int c) { if (r + p->h > wall->h || c + p->w > wall->w) return false; for (int i = 0; i < p->h; i++) { for (int j = 0; j < p->w; j++) { char x = p->cell[i][j]; if (x != '?' && x != wall->cell[r + i][c + j]) return false; } } return true;}/* 처음 맞는 자리를 *row, *col, *angle에 적고 참을 돌려준다. 없으면 거짓 */static bool find(const Grid *wall, const Grid *pattern, int *row, int *col, int *angle) { Grid turns[4]; turns[0] = *pattern; for (int k = 1; k < 4; k++) turns[k] = rotate(&turns[k - 1]); for (int r = 0; r < wall->h; r++) { for (int c = 0; c < wall->w; c++) { for (int k = 0; k < 4; k++) { if (fits(wall, &turns[k], r, c)) { *row = r + 1; *col = c + 1; *angle = k * 90; return true; } } } } return false;}static void read_grid(Grid *g) { scanf("%d %d", &g->h, &g->w); for (int i = 0; i < g->h; i++) scanf("%20s", g->cell[i]);}int main(void) { static Grid wall, pattern; int q; read_grid(&wall); scanf("%d", &q); while (q-- > 0) { int r, c, angle; read_grid(&pattern); if (find(&wall, &pattern, &r, &c, &angle)) printf("%d %d %d\n", r, c, angle); else printf("-1\n"); } return 0;}
Craykonmain.cray · 90 lines
// 무늬를 시계 방향으로 90도 돌린 새 무늬를 돌려준다돌리기(무늬){ h = 무늬.Count; w = 무늬[0].Length; 돌린 = []; for (i = 0; i < w; i++) { 줄 = ""; for (j = 0; j < h; j++) { 줄 = 줄 + 무늬[h - 1 - j][i]; } 돌린.Add(줄); } return 돌린;}// 무늬의 왼쪽 위를 벽의 (r, c)에 댔을 때 모든 칸이 맞는가맞나(벽, 무늬, r, c){ h = 무늬.Count; w = 무늬[0].Length; if (r + h > 벽.Count || c + w > 벽[0].Length) { return false; } for (i = 0; i < h; i++) { for (j = 0; j < w; j++) { if (무늬[i][j] != "?" && 무늬[i][j] != 벽[r + i][c + j]) { return false; } } } return true;}// 처음 맞는 [줄, 칸, 각]을 돌려준다. 없으면 빈값찾기(벽, 무늬){ 돌린것들 = [무늬]; for (k = 1; k < 4; k++) { 돌린것들.Add(돌리기(돌린것들[k - 1])); } for (r = 0; r < 벽.Count; r++) { for (c = 0; c < 벽[0].Length; c++) { for (k = 0; k < 4; k++) { if (맞나(벽, 돌린것들[k], r, c)) { return [r + 1, c + 1, k * 90]; } } } } return null;}// 판 하나(첫 줄 h w, 다음 h줄)를 읽어 문자열 목록으로 돌려준다판읽기(){ 크기 = Console.ReadNumbers(); 판 = []; for (i = 0; i < 크기[0]; i++) { 판.Add(Console.ReadLine().Trim()); } return 판;}벽 = 판읽기();q = Console.ReadLine().ToNumber();for (t = 0; t < q; t++){ 자리 = 찾기(벽, 판읽기()); if (자리 == null) { Console.WriteLine(-1); } else { Console.WriteLine(자리[0] + " " + 자리[1] + " " + 자리[2]); }}