简体   繁体   中英

search a word in 2d array movement is only top-bottom and left-right in java

Given a 2D matrix of characters and a target word, write a function that returns whether the word can be found in the matrix by going left-to-right, or up-to-down. For example, given the following matrix: [['F', 'A', 'C', 'I'], ['O', 'B', 'Q', 'P'], ['A', 'N', 'O', 'B'], ['M', 'A', 'S', 'S']]
and the target word 'FOAM', you should return true, since it's the leftmost column. Similarly, given the target word 'MASS', you should return true, since it's the last row.

import java.io.*; 
import java.util.*; 
public class Exercise6 
{ 
    static int R, C; 
    static int[] x = { 1, 0}; 
    static int[] y = { 0, 1}; 
    static boolean search2D(char[][] grid, int row, int col, String word) 
    {  
            if (grid[row][col] != word.charAt(0)) 
                return false; 
            int len = word.length();  
            for (int dir = 0; dir < 2; dir++) 
            { 
                int k, rd = row + x[dir], cd = col + y[dir];  
                for (k = 1; k < len; k++) 
                { 
                    if (rd >= R || rd < 0 || cd >= C || cd < 0) 
                        break; 
                    if (grid[rd][cd] != word.charAt(k)) 
                        break;  
                    rd += x[dir]; 
                    cd += y[dir]; 
                }  
                if (k == len) 
                    return true; 
            } 
        return false; 
    } 
    static void patternSearch(char[][] grid, String word) 
    { 
        for (int row = 0; row < R; row++) 
        { 
            for (int col = 0; col < C; col++) 
            { 
                if (search2D(grid, row, col, word)) 
                    System.out.println("pattern "+word+" found "); 
            } 
        } 
    } 
    public static void main(String args[]) 
    { 
            R = 4; 
            C = 4; 
            char[][] grid = {{'F', 'A', 'C', 'I'}, 
                {'O', 'B', 'Q', 'P'}, 
                    {'A', 'N', 'O', 'B'}, 
            {'M', 'A', 'S', 'S'}} ; 
            patternSearch(grid, "ABNA"); 
            System.out.println(); 
            patternSearch(grid, "MASS"); 
    } 
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM