give java code for this
बनाया गया: 17 जून 2025
बनाया गया: 17 जून 2025
Below is a straightforward-but-efficient Java solution that counts every occurrence of the target word in all 8 possible directions (horizontal, vertical, and the two diagonals, both forwards and backwards).
It simply walks the grid from every starting cell whose first character matches the first character of the word.
javaimport java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main { // 8 direction unit-steps: ↖ ↑ ↗ ← → ↙ ↓ ↘ private static final int[] DX = {-1, -1, -1, 0, 0, 1, 1, 1}; private static final int[] DY = {-1, 0, 1, -1, 1,-1, 0, 1}; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine().trim()); char[][] grid = new char[n][n]; for (int i = 0; i < n; i++) { String line = br.readLine().trim(); // remove any spaces just in case (defensive) line = line.replaceAll("\\s+", ""); grid[i] = line.toCharArray(); } String word = br.readLine().trim(); int wordLen = word.length(); int total = 0; for (int r = 0; r < n; r++) { for (int c = 0; c < n; c++) { if (grid[r][c] != word.charAt(0)) continue; // try every direction for (int dir = 0; dir < 8; dir++) { int x = r, y = c; int k; for (k = 1; k < wordLen; k++) { x += DX[dir]; y += DY[dir]; if (x < 0 || y < 0 || x >= n || y >= n) break; if (grid[x][y] != word.charAt(k)) break; } if (k == wordLen) { // full match total++; } } } } System.out.println(total); } }
N
, the N×N
grid, then the word to search.DX
, DY
arrays).wordLen
steps successfully, that’s one occurrence.This runs in O(N² * 8 * L)
time (L =
word length) with O(1)
extra space—fast enough for typical contest constraints.
for 3 ctt cat ctt cat answer 4 but your code giving 3
pythongrid = ["ctt","cat","ctt"] word = "cat" n = len(grid) DX = [-1,-1,-1,0,0,1,1,1] DY = [-1,0,1,-1,1,-1,0,1] count=0 for r in range(n): for c in range(n): if grid[r][c]!=word[0]: continue for d in range(8): x=r; y=c; k=1 while k<len(word): x+=DX[d]; y+=DY[d] if x<0 or y<0 or x>=n or y>=n: break if grid[x][y]!=word[k]: break k+=1 if k==len(word): count+=1 print(count)
pythongrid2 = ["ctt","cat","ctt"] n=len(grid2) word="cat" sequences=[] for r in range(n): for c in range(n): for d in range(8): path=[] x=r; y=c for k in range(len(word)): if x<0 or y<0 or x>=n or y>=n: break path.append(grid2[x][y]) x+=DX[d]; y+=DY[d] if len(path)==len(word): sequences.append(''.join(path)) print(sequences.count(word))
pythonsequences.count("tac") 3
pythondef count_word(grid, word): n=len(grid) count=0 for r in range(n): for c in range(n): if grid[r][c]!=word[0]: continue for d in range(8): x=r; y=c; k=1 while k<len(word): x+=DX[d]; y+=DY[d] if x<0 or y<0 or x>=n or y>=n: break if grid[x][y]!=word[k]: break k+=1 if k==len(word): count+=1 return count def count_word_any(grid, word): n=len(grid) count=0 paths=[] for r in range(n): for c in range(n): for d in range(8): path=[] x=r; y=c for k in range(len(word)): if x<0 or y<0 or x>=n or y>=n: break path.append(grid[x][y]) x+=DX[d]; y+=DY[d] if len(path)==len(word): if ''.join(path)==word: count+=1 paths.append(((r,c),d)) return count, paths grid2 = ["ctt","tat","ctt"] print(count_word(grid2,"cat"))
pythondef count_word_4dirs(grid, word): n=len(grid) dx=[-1,1,0,0] dy=[0,0,-1,1] count=0 for r in range(n): for c in range(n): if grid[r][c]!=word[0]: continue for d in range(4): x=r; y=c; k=1 while k<len(word): x+=dx[d]; y+=dy[d] if x<0 or y<0 or x>=n or y>=n: break if grid[x][y]!=word[k]: break k+=1 if k==len(word): count+=1 return count print(count_word_4dirs(grid2,"cat"))
pythondirections = [(-1,-1),(-1,0),(-1,1),(0,-1),(0,1),(1,-1),(1,0),(1,1)] grid2 = ["ctt","cat","ctt"] paths=[] for r in range(3): for c in range(3): for d_idx,(dx,dy) in enumerate(directions): x=r; y=c; s="" for k in range(len("cat")): if 0<=x<3 and 0<=y<3: s+=grid2[x][y] x+=dx; y+=dy else: s=None break if s=="cat": paths.append(((r,c),directions[d_idx])) paths [((0, 0), (1, 1)), ((1, 0), (0, 1)), ((2, 0), (-1, 1))]
Let’s walk through that 3 × 3 example by hand to see every place c a t really shows up.
textRow / Col indices 0 1 2 +---+---+---+ 0 | c | t | t | +---+---+---+ 1 | c | a | t | +---+---+---+ 2 | c | t | t | +---+---+---+
start → direction | cells visited | letters |
---|---|---|
(0,0) → down-right | (0,0) → (1,1) → (2,2) | c a t ✅ |
(1,0) → right | (1,0) → (1,1) → (1,2) | c a t ✅ |
(2,0) → up-right | (2,0) → (1,1) → (0,2) | c a t ✅ |
No other direction from any c completes the word without leaving the grid or mismatching a letter.
So there are exactly 3 occurrences.
Why the official answer can’t be 4
Unless the grid (or the counting rule) is different from what you typed, there just isn’t a fourth straight-line “cat.”
- Counting the reverse word t a c separately would bring the total to 6, not 4.
- Counting a palindrome twice doesn’t apply here because cat is not a palindrome.
ctt
, cat
, ctt
.line = line.trim().replaceAll("\\s+","")
) to guard against this; if you removed that line, stray spaces could change the grid.(If the word weretext3 ctt cat ctt cat
ctt
, the count is 4.)You’ll need to find the extra occurrence the judge is counting – usually that means the grid or counting rule is not what we assumed. Double-check the raw sample input exactly as the judge feeds it (including case and spaces). Once you spot the difference, the same core algorithm will still work after you read the data correctly.